repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_feedback_screen.dart
|
import 'dart:async';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
import '../../localization/extension.dart';
import '../../scaffold_messenger/service.dart';
import '../../screens/base.dart';
class SettingsFeedbackScreen extends StatefulHookConsumerWidget {
const SettingsFeedbackScreen({super.key});
@override
ConsumerState<SettingsFeedbackScreen> createState() =>
_SettingsFeedbackScreenState();
}
class _SettingsFeedbackScreenState
extends ConsumerState<SettingsFeedbackScreen> {
String? info;
@override
void initState() {
super.initState();
_loadAppInformation();
}
Future<void> _loadAppInformation() async {
final packageInfo = await PackageInfo.fromPlatform();
var textualInfo =
'Maily v${packageInfo.version}+${packageInfo.buildNumber}\n'
'Platform '
'${Platform.operatingSystem} ${Platform.operatingSystemVersion}\n';
final deviceInfoPlugin = DeviceInfoPlugin();
if (Platform.isAndroid) {
final androidInfo = await deviceInfoPlugin.androidInfo;
textualInfo += '${androidInfo.manufacturer}/${androidInfo.model} '
'(${androidInfo.device})\nAndroid ${androidInfo.version.release} '
'with API level ${androidInfo.version.sdkInt}';
} else if (Platform.isIOS) {
final iosInfo = await deviceInfoPlugin.iosInfo;
textualInfo += '${iosInfo.localizedModel}\n'
'${iosInfo.systemName}/${iosInfo.systemVersion}\n';
} else if (Platform.isWindows) {
final windowsInfo = await deviceInfoPlugin.windowsInfo;
textualInfo += '${windowsInfo.productName}\n${windowsInfo.majorVersion}.'
'${windowsInfo.minorVersion} ${windowsInfo.displayVersion}\n';
} else if (Platform.isMacOS) {
final macOsInfo = await deviceInfoPlugin.macOsInfo;
textualInfo += '${macOsInfo.model}\n'
'MacOS ${macOsInfo.majorVersion}.${macOsInfo.minorVersion} '
'${macOsInfo.osRelease}\n';
}
setState(() {
info = textualInfo;
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final localizations = ref.text;
return BasePage(
title: localizations.feedbackTitle,
content: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8),
child: Text(
localizations.feedbackIntro,
style: theme.textTheme.titleMedium,
),
),
if (info == null)
const Padding(
padding: EdgeInsets.all(8),
child: PlatformProgressIndicator(),
)
else ...[
Padding(
padding: const EdgeInsets.all(8),
child: Text(
localizations.feedbackProvideInfoRequest,
style: theme.textTheme.bodySmall,
),
),
Padding(
padding: const EdgeInsets.all(8),
child: Text(info ?? ''),
),
Padding(
padding: const EdgeInsets.all(8),
child: PlatformIconButton(
icon: Icon(CommonPlatformIcons.copy),
onPressed: () {
Clipboard.setData(ClipboardData(text: info ?? ''));
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.feedbackResultInfoCopied,
);
},
),
),
],
Padding(
padding: const EdgeInsets.all(8),
child: PlatformTextButton(
child: Text(localizations.feedbackActionSuggestFeature),
onPressed: () async {
await launcher
.launchUrl(Uri.parse('https://maily.userecho.com/'));
},
),
),
Padding(
padding: const EdgeInsets.all(8),
child: PlatformTextButton(
child: Text(localizations.feedbackActionReportProblem),
onPressed: () async {
await launcher
.launchUrl(Uri.parse('https://maily.userecho.com/'));
},
),
),
Padding(
padding: const EdgeInsets.all(8),
child: PlatformTextButton(
child: Text(localizations.feedbackActionHelpDeveloping),
onPressed: () async {
await launcher.launchUrl(
Uri.parse(
'https://github.com/Enough-Software/enough_mail_app',
),
);
},
),
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_swipe_screen.dart
|
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../localization/extension.dart';
import '../../models/swipe.dart';
import '../../screens/base.dart';
import '../../util/localized_dialog_helper.dart';
import '../provider.dart';
class SettingsSwipeScreen extends ConsumerWidget {
const SettingsSwipeScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(settingsProvider);
final leftToRightAction = settings.swipeLeftToRightAction;
final rightToLeftAction = settings.swipeRightToLeftAction;
final theme = Theme.of(context);
final localizations = ref.text;
return BasePage(
title: localizations.swipeSettingTitle,
content: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
localizations.swipeSettingLeftToRightLabel,
style: theme.textTheme.bodySmall,
),
_SwipeSetting(
swipeAction: leftToRightAction,
isLeftToRight: true,
),
const Divider(),
Text(
localizations.swipeSettingRightToLeftLabel,
style: theme.textTheme.bodySmall,
),
_SwipeSetting(
swipeAction: rightToLeftAction,
isLeftToRight: false,
),
],
),
),
),
),
);
}
}
class _SwipeSetting extends HookConsumerWidget {
const _SwipeSetting({
required this.swipeAction,
required this.isLeftToRight,
});
final bool isLeftToRight;
final SwipeAction swipeAction;
@override
Widget build(BuildContext context, WidgetRef ref) {
final localizations = ref.text;
final swipeActionState = useState(swipeAction);
Future<SwipeAction?> selectSwipe(SwipeAction current) async {
final action = await LocalizedDialogHelper.showWidgetDialog(
ref,
SizedBox(
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width * 0.7,
child: GridView.count(
crossAxisCount: 2,
// shrinkWrap: true,
children: SwipeAction.values
.map(
(action) => PlatformTextButton(
child: Stack(
children: [
_SwipeWidget(
swipeAction: action,
isSmall: true,
),
if (action == current)
Align(
alignment: Alignment.topLeft,
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: Icon(
Icons.check,
color: Theme.of(context).colorScheme.secondary,
),
),
),
],
),
onPressed: () {
context.pop(action);
},
),
)
.toList(),
),
),
title: isLeftToRight
? localizations.swipeSettingLeftToRightLabel
: localizations.swipeSettingRightToLeftLabel,
defaultActions: DialogActions.cancel,
);
if (action == false) {
return null;
}
return action;
}
Future<void> onPressed() async {
final action = await selectSwipe(swipeActionState.value);
if (action != null) {
swipeActionState.value = action;
final settings = ref.read(settingsProvider);
final newSettings = isLeftToRight
? settings.copyWith(swipeLeftToRightAction: action)
: settings.copyWith(swipeRightToLeftAction: action);
await ref.read(settingsProvider.notifier).update(
newSettings,
);
}
}
return Row(
children: [
PlatformTextButton(
onPressed: onPressed,
child: _SwipeWidget(
swipeAction: swipeActionState.value,
),
),
PlatformTextButtonIcon(
onPressed: onPressed,
icon: const Icon(Icons.edit),
label: Text(localizations.swipeSettingChangeAction),
),
],
);
}
}
class _SwipeWidget extends ConsumerWidget {
const _SwipeWidget({required this.swipeAction, this.isSmall = false});
final SwipeAction swipeAction;
final bool isSmall;
@override
Widget build(BuildContext context, WidgetRef ref) {
final localizations = ref.text;
return Padding(
padding: const EdgeInsets.all(4),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Container(
color: swipeAction.colorBackground,
width: 128,
height: 128,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Icon(
swipeAction.icon,
color: swipeAction.colorIcon,
),
),
Text(
swipeAction.name(localizations),
style: TextStyle(
color: swipeAction.colorForeground,
fontSize: isSmall ? 10.0 : 12.0,
),
// overflow: TextOverflow.ellipsis,
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/theme/provider.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'provider.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$defaultColorSeedHash() => r'c2bdee6a44fad5bfcada3d31af099906bb24c988';
/// The default color provider
///
/// Copied from [defaultColorSeed].
@ProviderFor(defaultColorSeed)
final defaultColorSeedProvider = Provider<Color>.internal(
defaultColorSeed,
name: r'defaultColorSeedProvider',
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
? null
: _$defaultColorSeedHash,
dependencies: null,
allTransitiveDependencies: null,
);
typedef DefaultColorSeedRef = ProviderRef<Color>;
String _$themeFinderHash() => r'484171788a33fa10e91e0f085a1c87cb4a29d8f0';
/// Copied from Dart SDK
class _SystemHash {
_SystemHash._();
static int combine(int hash, int value) {
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + value);
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
return hash ^ (hash >> 6);
}
static int finish(int hash) {
// ignore: parameter_assignments
hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
// ignore: parameter_assignments
hash = hash ^ (hash >> 11);
return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
}
}
abstract class _$ThemeFinder extends BuildlessNotifier<ThemeSettingsData> {
late final BuildContext context;
ThemeSettingsData build({
required BuildContext context,
});
}
/// Provides the settings
///
/// Copied from [ThemeFinder].
@ProviderFor(ThemeFinder)
const themeFinderProvider = ThemeFinderFamily();
/// Provides the settings
///
/// Copied from [ThemeFinder].
class ThemeFinderFamily extends Family<ThemeSettingsData> {
/// Provides the settings
///
/// Copied from [ThemeFinder].
const ThemeFinderFamily();
/// Provides the settings
///
/// Copied from [ThemeFinder].
ThemeFinderProvider call({
required BuildContext context,
}) {
return ThemeFinderProvider(
context: context,
);
}
@override
ThemeFinderProvider getProviderOverride(
covariant ThemeFinderProvider provider,
) {
return call(
context: provider.context,
);
}
static const Iterable<ProviderOrFamily>? _dependencies = null;
@override
Iterable<ProviderOrFamily>? get dependencies => _dependencies;
static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null;
@override
Iterable<ProviderOrFamily>? get allTransitiveDependencies =>
_allTransitiveDependencies;
@override
String? get name => r'themeFinderProvider';
}
/// Provides the settings
///
/// Copied from [ThemeFinder].
class ThemeFinderProvider
extends NotifierProviderImpl<ThemeFinder, ThemeSettingsData> {
/// Provides the settings
///
/// Copied from [ThemeFinder].
ThemeFinderProvider({
required BuildContext context,
}) : this._internal(
() => ThemeFinder()..context = context,
from: themeFinderProvider,
name: r'themeFinderProvider',
debugGetCreateSourceHash:
const bool.fromEnvironment('dart.vm.product')
? null
: _$themeFinderHash,
dependencies: ThemeFinderFamily._dependencies,
allTransitiveDependencies:
ThemeFinderFamily._allTransitiveDependencies,
context: context,
);
ThemeFinderProvider._internal(
super._createNotifier, {
required super.name,
required super.dependencies,
required super.allTransitiveDependencies,
required super.debugGetCreateSourceHash,
required super.from,
required this.context,
}) : super.internal();
final BuildContext context;
@override
ThemeSettingsData runNotifierBuild(
covariant ThemeFinder notifier,
) {
return notifier.build(
context: context,
);
}
@override
Override overrideWith(ThemeFinder Function() create) {
return ProviderOverride(
origin: this,
override: ThemeFinderProvider._internal(
() => create()..context = context,
from: from,
name: null,
dependencies: null,
allTransitiveDependencies: null,
debugGetCreateSourceHash: null,
context: context,
),
);
}
@override
NotifierProviderElement<ThemeFinder, ThemeSettingsData> createElement() {
return _ThemeFinderProviderElement(this);
}
@override
bool operator ==(Object other) {
return other is ThemeFinderProvider && other.context == context;
}
@override
int get hashCode {
var hash = _SystemHash.combine(0, runtimeType.hashCode);
hash = _SystemHash.combine(hash, context.hashCode);
return _SystemHash.finish(hash);
}
}
mixin ThemeFinderRef on NotifierProviderRef<ThemeSettingsData> {
/// The parameter `context` of this provider.
BuildContext get context;
}
class _ThemeFinderProviderElement
extends NotifierProviderElement<ThemeFinder, ThemeSettingsData>
with ThemeFinderRef {
_ThemeFinderProviderElement(super.provider);
@override
BuildContext get context => (origin as ThemeFinderProvider).context;
}
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/theme/model.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ThemeSettings _$ThemeSettingsFromJson(Map<String, dynamic> json) =>
ThemeSettings(
themeModeSetting: $enumDecodeNullable(
_$ThemeModeSettingEnumMap, json['themeModeSetting']) ??
ThemeModeSetting.system,
themeDarkStartTime: json['themeDarkStartTime'] == null
? const TimeOfDay(hour: 22, minute: 0)
: _timeOfDayFromJson(
json['themeDarkStartTime'] as Map<String, dynamic>),
themeDarkEndTime: json['themeDarkEndTime'] == null
? const TimeOfDay(hour: 7, minute: 0)
: _timeOfDayFromJson(
json['themeDarkEndTime'] as Map<String, dynamic>),
colorSchemeSeed:
_colorFromJson(json['colorSchemeSeed'] as Map<String, dynamic>),
);
Map<String, dynamic> _$ThemeSettingsToJson(ThemeSettings instance) =>
<String, dynamic>{
'themeModeSetting': _$ThemeModeSettingEnumMap[instance.themeModeSetting]!,
'themeDarkStartTime': _timeOfDayToJson(instance.themeDarkStartTime),
'themeDarkEndTime': _timeOfDayToJson(instance.themeDarkEndTime),
'colorSchemeSeed': _colorToJson(instance.colorSchemeSeed),
};
const _$ThemeModeSettingEnumMap = {
ThemeModeSetting.light: 'light',
ThemeModeSetting.dark: 'dark',
ThemeModeSetting.system: 'system',
ThemeModeSetting.custom: 'custom',
};
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/theme/provider.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../app_lifecycle/provider.dart';
import '../provider.dart';
import 'model.dart';
part 'provider.g.dart';
/// The default color provider
@Riverpod(keepAlive: true)
Color defaultColorSeed(DefaultColorSeedRef ref) => Colors.green;
/// Provides the settings
@Riverpod(keepAlive: true)
class ThemeFinder extends _$ThemeFinder {
@override
ThemeSettingsData build({required BuildContext context}) {
final themeSettings = ref.watch(
settingsProvider.select((value) => value.themeSettings),
);
ref.watch(appIsResumedProvider);
final defaultColor = ref.watch(defaultColorSeedProvider);
return _fromThemeSettings(
themeSettings,
defaultColor,
context: context,
);
}
static ThemeSettingsData _fromThemeSettings(
ThemeSettings settings,
Color defaultColor, {
BuildContext? context,
}) {
final mode = settings.getCurrentThemeMode();
final brightness = _resolveBrightness(mode, context);
final dark = _generateMaterialTheme(
Brightness.dark,
settings.colorSchemeSeed ?? defaultColor,
);
final light = _generateMaterialTheme(
Brightness.light,
settings.colorSchemeSeed ?? defaultColor,
);
final cupertino = _generateCupertinoTheme(
brightness,
settings.colorSchemeSeed ?? defaultColor,
);
return ThemeSettingsData(
brightness: brightness,
lightTheme: light,
darkTheme: dark,
themeMode: mode,
cupertinoTheme: cupertino,
);
}
static Brightness _resolveBrightness(
ThemeMode mode,
BuildContext? context,
) {
switch (mode) {
case ThemeMode.system:
return context != null
? MediaQuery.platformBrightnessOf(context)
: Brightness.light;
case ThemeMode.light:
return Brightness.light;
case ThemeMode.dark:
return Brightness.dark;
}
}
static ThemeData _generateMaterialTheme(Brightness brightness, Color color) =>
color is MaterialColor
? ThemeData(
brightness: brightness,
primarySwatch: color,
useMaterial3: false,
)
: ThemeData(
brightness: brightness,
colorSchemeSeed: color,
useMaterial3: true,
);
static CupertinoThemeData _generateCupertinoTheme(
Brightness brightness,
Color color,
) =>
CupertinoThemeData(
brightness: brightness,
primaryColor: color,
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/theme/model.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
part 'model.g.dart';
/// Defines the current theme mode
enum ThemeModeSetting {
/// always use a light theme
light,
/// always use a dark theme
dark,
/// use the system theme
system,
/// use a custom theme in which you switch between dark and light depending
/// on the time of day
custom,
}
//// Contains the settings for the theme
@JsonSerializable()
class ThemeSettings {
/// Creates settings for the theme
const ThemeSettings({
this.themeModeSetting = ThemeModeSetting.system,
this.themeDarkStartTime = const TimeOfDay(hour: 22, minute: 0),
this.themeDarkEndTime = const TimeOfDay(hour: 7, minute: 0),
this.colorSchemeSeed,
});
/// Creates settings from the given [json]
factory ThemeSettings.fromJson(Map<String, dynamic> json) =>
_$ThemeSettingsFromJson(json);
/// Converts these settings to JSON
Map<String, dynamic> toJson() => _$ThemeSettingsToJson(this);
/// The current theme mode
final ThemeModeSetting themeModeSetting;
/// The time of day when the dark theme should be active
@JsonKey(fromJson: _timeOfDayFromJson, toJson: _timeOfDayToJson)
final TimeOfDay themeDarkStartTime;
/// The time of day when the dark theme should be inactive
@JsonKey(fromJson: _timeOfDayFromJson, toJson: _timeOfDayToJson)
final TimeOfDay themeDarkEndTime;
/// The color scheme seed
@JsonKey(fromJson: _colorFromJson, toJson: _colorToJson)
final Color? colorSchemeSeed;
/// Standard colors
static List<Color> get availableColors => const [
Colors.red,
Colors.green,
Colors.yellow,
Colors.blue,
Colors.grey,
Colors.blueGrey,
Colors.lightBlue,
Colors.cyan,
Colors.teal,
Colors.indigo,
Colors.lightGreen,
Colors.orange,
Colors.deepOrange,
Colors.purple,
Colors.deepPurple,
Colors.brown,
Colors.amber,
Colors.lime,
Colors.pink,
];
/// Returns the current theme mode
ThemeMode getCurrentThemeMode() {
switch (themeModeSetting) {
case ThemeModeSetting.light:
return ThemeMode.light;
case ThemeModeSetting.dark:
return ThemeMode.dark;
case ThemeModeSetting.system:
return ThemeMode.system;
case ThemeModeSetting.custom:
final now = _convertTimeOfDayToInt(TimeOfDay.now());
return now > _convertTimeOfDayToInt(themeDarkStartTime) ||
now < _convertTimeOfDayToInt(themeDarkEndTime)
? ThemeMode.dark
: ThemeMode.light;
}
}
/// Returns a copy of these settings with the given properties
ThemeSettings copyWith({
Color? colorSchemeSeed,
TimeOfDay? themeDarkStartTime,
TimeOfDay? themeDarkEndTime,
ThemeModeSetting? themeModeSetting,
}) =>
ThemeSettings(
colorSchemeSeed: colorSchemeSeed ?? this.colorSchemeSeed,
themeDarkStartTime: themeDarkStartTime ?? this.themeDarkStartTime,
themeDarkEndTime: themeDarkEndTime ?? this.themeDarkEndTime,
themeModeSetting: themeModeSetting ?? this.themeModeSetting,
);
}
Map<String, dynamic> _timeOfDayToJson(TimeOfDay value) => {
'hour': value.hour,
'minute': value.minute,
};
TimeOfDay _timeOfDayFromJson(Map<String, dynamic> json) => TimeOfDay(
hour: json['hour'],
minute: json['minute'],
);
int _convertTimeOfDayToInt(TimeOfDay input) => input.hour * 100 + input.minute;
Map<String, dynamic> _colorToJson(Color? value) {
if (value == null) {
return {};
}
final index = ThemeSettings.availableColors.indexOf(value);
return {
'index': index,
'color': value.value,
};
}
Color? _colorFromJson(Map<String, dynamic> json) {
final index = json['index'] as int?;
if (index != null &&
index > 0 &&
index < ThemeSettings.availableColors.length) {
return ThemeSettings.availableColors[index];
}
final color = json['color'] as int?;
if (color != null) {
return Color(color);
}
return null;
}
//// The actually applied theme data
@immutable
class ThemeSettingsData {
/// Creates the theme data
const ThemeSettingsData({
required this.brightness,
required this.darkTheme,
required this.lightTheme,
required this.themeMode,
required this.cupertinoTheme,
});
/// The current brightness
final Brightness brightness;
/// The current dark theme data
final ThemeData darkTheme;
/// The current bright theme data
final ThemeData lightTheme;
/// The (material) theme mode
final ThemeMode themeMode;
/// The cupertino theme data
final CupertinoThemeData cupertinoTheme;
@override
int get hashCode =>
darkTheme.hashCode ^ lightTheme.hashCode ^ themeMode.hashCode;
@override
bool operator ==(Object other) =>
other is ThemeSettingsData &&
other.darkTheme == darkTheme &&
other.lightTheme == lightTheme &&
other.themeMode == themeMode;
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/theme/icon_service.dart
|
import 'package:community_material_icon/community_material_icon.dart';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class IconService {
IconService._();
static final _instance = IconService._();
/// Returns the singleton instance
static IconService get instance => _instance;
static final _isCupertino = PlatformInfo.isCupertino;
IconData get share => _isCupertino ? CupertinoIcons.share : Icons.share;
IconData get location =>
_isCupertino ? CupertinoIcons.location : Icons.location_on_outlined;
IconData get email => _isCupertino ? CupertinoIcons.mail : Icons.email;
IconData get settings =>
_isCupertino ? CupertinoIcons.settings : Icons.settings;
IconData get about => _isCupertino ? CupertinoIcons.info : Icons.info_outline;
IconData get mediaFile =>
_isCupertino ? CupertinoIcons.doc : Icons.insert_drive_file_outlined;
IconData get mediaPhoto =>
_isCupertino ? CupertinoIcons.photo : Icons.photo_outlined;
IconData get mediaAudio =>
_isCupertino ? CupertinoIcons.music_note : Icons.audiotrack_outlined;
IconData get mediaVideo =>
_isCupertino ? CupertinoIcons.videocam : Icons.video_collection_outlined;
IconData get mediaGif => Icons.gif;
IconData get mediaSticker => CommunityMaterialIcons.sticker;
IconData get appointment =>
_isCupertino ? CupertinoIcons.calendar : Icons.calendar_today;
IconData get add => _isCupertino ? CupertinoIcons.add : Icons.add;
IconData get retry =>
_isCupertino ? CupertinoIcons.arrow_clockwise : Icons.repeat;
IconData getMessageIsSeen(bool isSeen) =>
isSeen ? messageIsSeen : messageIsNotSeen;
IconData get messageIsSeen =>
_isCupertino ? CupertinoIcons.circle : Icons.circle_outlined;
IconData get messageIsNotSeen =>
_isCupertino ? CupertinoIcons.circle_fill : Icons.circle;
IconData getMessageIsFlagged(bool isFlagged) =>
isFlagged ? messageIsFlagged : messageIsNotFlagged;
IconData get messageIsFlagged =>
_isCupertino ? CupertinoIcons.flag_fill : Icons.flag;
IconData get messageIsNotFlagged =>
_isCupertino ? CupertinoIcons.flag : Icons.flag_outlined;
IconData get messageActionReply =>
_isCupertino ? CupertinoIcons.reply : Icons.reply;
IconData get messageActionReplyAll =>
_isCupertino ? CupertinoIcons.reply_all : Icons.reply_all;
IconData get messageActionForward =>
_isCupertino ? CupertinoIcons.arrowshape_turn_up_right : Icons.forward;
IconData get messageActionForwardAsAttachment => Icons.forward_to_inbox;
IconData get messageActionForwardAttachments => Icons.attach_file;
IconData get messageActionMoveToInbox => Icons.move_to_inbox;
IconData get messageActionDelete => _isCupertino
? CupertinoIcons.delete
: CommunityMaterialIcons.trash_can_outline;
IconData get messageActionMove => _isCupertino
? CupertinoIcons.folder
: CommunityMaterialIcons.file_move_outline;
IconData get messageActionMoveToJunk => CommunityMaterialIcons.bug_outline;
IconData get messageActionMoveFromJunkToInbox =>
_isCupertino ? CupertinoIcons.checkmark : Icons.check;
IconData get messageActionArchive => _isCupertino
? CupertinoIcons.archivebox
: CommunityMaterialIcons.archive_outline;
IconData get messageActionRedirect =>
_isCupertino ? CupertinoIcons.arrow_branch : Icons.compare_arrows;
IconData get messageActionViewInSafeMode =>
_isCupertino ? CupertinoIcons.lock : Icons.lock;
IconData get messageActionAddNotification =>
_isCupertino ? CupertinoIcons.alarm : Icons.notification_add;
IconData get folderGeneric => CommunityMaterialIcons.folder_outline;
IconData get folderInbox => CommunityMaterialIcons.inbox;
IconData get folderDrafts => CommunityMaterialIcons.email_edit_outline;
IconData get folderTrash => CommunityMaterialIcons.trash_can_outline;
IconData get folderSent => CommunityMaterialIcons.inbox_arrow_up;
IconData get folderArchive => CommunityMaterialIcons.archive_outline;
IconData get folderJunk => CommunityMaterialIcons.bug_outline;
IconData getForMediaType(MediaType? mediaType) {
if (mediaType == null) {
return Icons.attachment;
}
switch (mediaType.top) {
case MediaToptype.text:
return Icons.short_text;
case MediaToptype.image:
return Icons.image;
case MediaToptype.audio:
return Icons.audiotrack;
case MediaToptype.video:
return Icons.ondemand_video;
case MediaToptype.application:
return Icons.apps;
case MediaToptype.multipart:
return Icons.apps;
case MediaToptype.message:
return Icons.message;
case MediaToptype.model:
return Icons.attachment;
case MediaToptype.font:
return Icons.font_download;
case MediaToptype.other:
return Icons.attachment;
// ignore: no_default_cases
default:
return Icons.attachment;
}
}
IconData getForMailbox(Mailbox mailbox) {
var iconData = folderGeneric;
if (mailbox.isInbox) {
iconData = folderInbox;
} else if (mailbox.isDrafts) {
iconData = folderDrafts;
} else if (mailbox.isTrash) {
iconData = folderTrash;
} else if (mailbox.isSent) {
iconData = folderSent;
} else if (mailbox.isArchive) {
iconData = folderArchive;
} else if (mailbox.isJunk) {
iconData = folderJunk;
}
return iconData;
}
static Widget buildNumericIcon(
BuildContext context,
int value, {
double? size,
}) {
switch (value) {
case 1:
return Icon(Icons.looks_one_outlined, size: size);
case 2:
return Icon(Icons.looks_two_outlined, size: size);
case 3:
return Icon(Icons.looks_3_outlined, size: size);
case 4:
return Icon(Icons.looks_4_outlined, size: size);
case 5:
return Icon(Icons.looks_5_outlined, size: size);
case 6:
return Icon(Icons.looks_6_outlined, size: size);
default:
final style = size == null ? null : TextStyle(fontSize: size * 0.8);
final borderColor = (Theme.of(context).brightness == Brightness.dark)
? const Color(0xffeeeeee)
: const Color(0xff000000);
return Container(
decoration: BoxDecoration(border: Border.all(color: borderColor)),
child: Text(value.toString(), style: style),
);
}
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/home/provider.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'provider.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$settingsUiElementsHash() =>
r'6f166928555e263afd52c81de4234103fe1f6c30';
/// See also [SettingsUiElements].
@ProviderFor(SettingsUiElements)
final settingsUiElementsProvider =
NotifierProvider<SettingsUiElements, void>.internal(
SettingsUiElements.new,
name: r'settingsUiElementsProvider',
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
? null
: _$settingsUiElementsHash,
dependencies: null,
allTransitiveDependencies: null,
);
typedef _$SettingsUiElements = Notifier<void>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/home/provider.dart
|
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../../enough_mail_app.dart';
part 'provider.g.dart';
@Riverpod(keepAlive: true)
class SettingsUiElements extends _$SettingsUiElements {
@override
void build() {}
/// Generates the shown setting entries
List<UiSettingsElement> generate(
WidgetRef ref,
) =>
buildStandardElements(ref);
static List<UiSettingsElement> buildStandardElements(
WidgetRef ref,
) {
final text = ref.text;
final context = ref.context;
return [
UiSettingsElement(
type: UiSettingsType.security,
title: text.securitySettingsTitle,
onTap: () => context.pushNamed(Routes.settingsSecurity),
),
UiSettingsElement(
type: UiSettingsType.accounts,
title: text.settingsActionAccounts,
onTap: () => context.pushNamed(Routes.settingsAccounts),
),
UiSettingsElement(
type: UiSettingsType.swipe,
title: text.swipeSettingTitle,
onTap: () => context.pushNamed(Routes.settingsSwipe),
),
UiSettingsElement(
type: UiSettingsType.signature,
title: text.signatureSettingsTitle,
onTap: () => context.pushNamed(Routes.settingsSignature),
),
UiSettingsElement(
type: UiSettingsType.defaultSender,
title: text.defaultSenderSettingsTitle,
onTap: () => context.pushNamed(Routes.settingsDefaultSender),
),
UiSettingsElement(
type: UiSettingsType.design,
title: text.settingsActionDesign,
onTap: () => context.pushNamed(Routes.settingsDesign),
),
UiSettingsElement(
type: UiSettingsType.language,
title: text.languageSettingTitle,
onTap: () => context.pushNamed(Routes.settingsLanguage),
),
UiSettingsElement(
type: UiSettingsType.folders,
title: text.settingsFolders,
onTap: () => context.pushNamed(Routes.settingsFolders),
),
UiSettingsElement(
type: UiSettingsType.readReceipts,
title: text.settingsReadReceipts,
onTap: () => context.pushNamed(Routes.settingsReadReceipts),
),
UiSettingsElement(
type: UiSettingsType.reply,
title: text.replySettingsTitle,
onTap: () => context.pushNamed(Routes.settingsReplyFormat),
),
UiSettingsElement.divider(),
UiSettingsElement(
type: UiSettingsType.feedback,
title: text.settingsActionFeedback,
onTap: () => context.pushNamed(Routes.settingsFeedback),
),
UiSettingsElement(
type: UiSettingsType.about,
title: text.drawerEntryAbout,
onTap: () => LocalizedDialogHelper.showAbout(ref),
),
UiSettingsElement(
type: UiSettingsType.welcome,
title: text.settingsActionWelcome,
onTap: () => context.pushNamed(Routes.welcome),
),
];
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/home/screen.dart
|
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../localization/extension.dart';
import '../../screens/base.dart';
import 'model.dart';
import 'provider.dart';
/// Allows to personalize the app settings
class SettingsScreen extends ConsumerWidget {
/// Creates a new [SettingsScreen]
const SettingsScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final uiSettingElementsNotifier = ref.watch(
settingsUiElementsProvider.notifier,
);
final settingEntries = uiSettingElementsNotifier.generate(ref);
final localizations = ref.text;
Widget buildEntry(UiSettingsElement entry) {
if (entry.isDivider) return const Divider();
final subtitle = entry.subtitle;
final icon = entry.icon;
return PlatformListTile(
title: Text(entry.title),
subtitle: subtitle != null ? Text(subtitle) : null,
leading: icon != null ? Icon(icon) : null,
onTap: entry.onTap,
);
}
return BasePage(
title: localizations.settingsTitle,
content: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: settingEntries.map(buildEntry).toList(),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/home/model.dart
|
import 'package:flutter/widgets.dart';
/// Standard setting entries
enum UiSettingsType {
divider,
security,
accounts,
swipe,
signature,
defaultSender,
design,
language,
folders,
readReceipts,
reply,
feedback,
about,
welcome,
development,
}
/// A UI element for the settings screen
class UiSettingsElement {
/// Creates a new [UiSettingsElement]
const UiSettingsElement({
required this.title,
required this.onTap,
this.type,
this.subtitle,
this.icon,
});
/// Creates a new [UiSettingsElement] as a divider
UiSettingsElement.divider()
: this(
title: '',
onTap: null,
type: UiSettingsType.divider,
);
/// The title of the element
final String title;
/// The standard type of the element
final UiSettingsType? type;
/// The subtitle of the element
final String? subtitle;
/// The icon of the element
final IconData? icon;
/// The action when the element is tapped
final VoidCallback? onTap;
/// Is this element a divider?
bool get isDivider => type == UiSettingsType.divider;
}
/// Eases custom elements
extension UiSettingsElementsExtension on List<UiSettingsElement> {
/// Inserts an element after the element with the given type
void insertAfter(UiSettingsType type, UiSettingsElement element) {
final index = indexWhere((e) => e.type == type);
if (index == -1) {
add(element);
} else {
insert(index + 1, element);
}
}
/// Inserts an element before the element with the given type
void insertBefore(UiSettingsType type, UiSettingsElement element) {
final index = indexWhere((e) => e.type == type);
if (index == -1) {
insert(0, element);
} else {
insert(index, element);
}
}
/// Removes the element with the given type
void removeType(UiSettingsType type) {
removeWhere((e) => e.type == type);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src/settings
|
mirrored_repositories/enough_mail_app/lib/src/settings/home/home.dart
|
export 'model.dart';
export 'provider.dart';
export 'screen.dart';
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/account_add_screen.dart
|
import 'dart:async';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
import '../account/model.dart';
import '../account/provider.dart';
import '../extensions/extensions.dart';
import '../hoster/service.dart';
import '../localization/app_localizations.g.dart';
import '../localization/extension.dart';
import '../logger.dart';
import '../mail/provider.dart';
import '../oauth/oauth.dart';
import '../routes/routes.dart';
import '../util/modal_bottom_sheet_helper.dart';
import '../util/validator.dart';
import '../widgets/account_hoster_selector.dart';
import '../widgets/password_field.dart';
import 'base.dart';
/// Adds a new account
class AccountAddScreen extends ConsumerStatefulWidget {
/// Creates a new [AccountAddScreen]
const AccountAddScreen({
super.key,
});
@override
ConsumerState<AccountAddScreen> createState() => _AccountAddScreenState();
}
class _AccountAddScreenState extends ConsumerState<AccountAddScreen> {
static const int _stepEmail = 0;
static const int _stepPassword = 1;
static const int _stepAccountSetup = 2;
late int _availableSteps;
int _currentStep = 0;
int _progressedSteps = 0;
bool _isContinueAvailable = false;
bool? _isApplicationSpecificPasswordAcknowledged = false;
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _accountNameController = TextEditingController();
final _userNameController = TextEditingController();
final _accountNameNode = FocusNode();
bool _isProviderResolving = false;
MailHoster? _mailHoster;
final _isManualSettings = false;
bool _isAccountVerifying = false;
bool _isAccountVerified = false;
MailClient? _mailClient;
AppExtensionActionDescription? _extensionForgotPassword;
RealAccount? _realAccount;
Future<void> _navigateToManualSettings(
BuildContext context,
AppLocalizations localizations,
) async {
final selectedHoster =
await ModelBottomSheetHelper.showModalBottomSheet<MailHoster>(
context,
localizations.accountProviderStepTitle,
MailHosterSelector(
onSelected: (hoster) {
context.pop(hoster);
},
),
useScrollView: false,
appBarActions: [],
);
if (selectedHoster != null) {
// a standard hoster has been chosen,
// now query the password or start the oauth process:
setState(() {
_mailHoster = selectedHoster;
});
_onMailHosterChanged(selectedHoster, _emailController.text);
} else {
final account = MailAccount(
email: _emailController.text.trim(),
name: _userNameController.text.trim(),
incoming: const MailServerConfig(
authentication: PlainAuthentication('', ''),
serverConfig: ServerConfig.empty(),
),
outgoing: const MailServerConfig(
authentication: PlainAuthentication('', ''),
serverConfig: ServerConfig.empty(),
),
);
if (context.mounted) {
final editResult = await context.pushNamed<ConnectedAccount>(
Routes.accountServerDetails,
extra: RealAccount(account),
);
if (editResult is ConnectedAccount) {
setState(() {
_realAccount = RealAccount(editResult.mailAccount);
_mailClient = editResult.mailClient;
_currentStep = 2;
_isAccountVerified = true;
});
}
}
}
}
@override
void initState() {
_availableSteps = 3;
final accounts = ref.read(realAccountsProvider);
if (accounts.isNotEmpty) {
_userNameController.text = accounts.first.userName ?? '';
}
super.initState();
}
@override
void dispose() {
_accountNameController.dispose();
_emailController.dispose();
_passwordController.dispose();
_userNameController.dispose();
_accountNameNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// print('build: current step=$_currentStep');
final localizations = ref.text;
return BasePage(
title: localizations.addAccountTitle,
content: Column(
children: [
Expanded(
child: PlatformStepper(
onStepContinue: _isContinueAvailable
? () async {
final step = _currentStep + 1;
await _onStepProgressed(step);
}
: null,
onStepCancel: () => context.pop(),
currentStep: _currentStep,
onStepTapped: (index) {
if (index != _currentStep && index <= _progressedSteps) {
setState(() {
_currentStep = index;
_isContinueAvailable = true;
});
}
},
steps: [
_buildEmailStep(context, localizations),
_buildPasswordStep(context, localizations),
_buildAccountSetupStep(context, localizations),
],
),
),
],
),
);
}
Future<void> _onStepProgressed(int step) async {
if (step < _availableSteps) {
setState(() {
_currentStep = step;
_isContinueAvailable = false;
});
}
_progressedSteps = step;
switch (step - 1) {
case _stepEmail:
await _discover(_emailController.text);
break;
case _stepPassword:
final mailHoster = _mailHoster;
if (mailHoster != null) {
await _verifyAccount(mailHoster);
}
break;
case _stepAccountSetup:
await _finalizeAccount();
break;
}
}
Future _discover(String email) async {
// email address has been entered
if (!_isProviderResolving) {
setState(() {
_isProviderResolving = true;
});
}
if (kDebugMode) {
print('discover settings for $email');
}
final provider = await MailHosterService.instance.discover(email);
if (!mounted) {
// ignore if user has cancelled operation
return;
}
if (kDebugMode) {
print('done discovering settings: ${provider?.displayName}');
}
if (provider?.appSpecificPasswordSetupUrl != null) {
FocusManager.instance.primaryFocus?.unfocus();
}
_isApplicationSpecificPasswordAcknowledged = false;
final domainName = email.substring(email.lastIndexOf('@') + 1);
_accountNameController.text = domainName;
if (provider != null) {
_onMailHosterChanged(provider, email);
}
setState(() {
_isProviderResolving = false;
_mailHoster = provider;
_isContinueAvailable =
(provider != null) && _passwordController.text.isNotEmpty;
});
}
Future _loginWithOAuth(
MailHoster mailHoster,
OauthClient oauthClient,
String email,
) async {
setState(() {
_isAccountVerifying = true;
_currentStep = _stepAccountSetup;
_progressedSteps = _stepAccountSetup;
});
final token = await oauthClient.authenticate(email);
// when the user either has cancelled the verification,
// not granted the scope or the verification failed for other reasons,
// then token will be null
if (token == null) {
setState(() {
_isAccountVerifying = false;
_currentStep = _stepPassword;
_progressedSteps = _stepAccountSetup;
});
} else {
final domainName = email.substring(email.lastIndexOf('@') + 1);
final mailAccount = MailAccount.fromDiscoveredSettingsWithAuth(
name: domainName,
email: email,
auth: OauthAuthentication(email, token),
config: mailHoster.clientConfig,
);
final connectedAccount = await ref.read(
firstTimeMailClientSourceProvider(
account: RealAccount(mailAccount),
).future,
);
_mailClient = connectedAccount?.mailClient;
final isVerified = _mailClient?.isConnected ?? false;
if (connectedAccount != null && isVerified) {
if (mailHoster is GmailMailHoster || mailHoster is OutlookMailHoster) {
_realAccount = connectedAccount;
} else {
try {
final extensions = await AppExtension.loadFor(mailAccount);
_realAccount = connectedAccount.copyWith(appExtensions: extensions);
} catch (e, s) {
logger.e(
'Unable to load app extensions for ${mailAccount.email}: $e',
error: e,
stackTrace: s,
);
}
}
} else {
FocusManager.instance.primaryFocus?.unfocus();
}
setState(() {
_isAccountVerifying = false;
_isAccountVerified = isVerified;
_isContinueAvailable =
isVerified && _userNameController.text.trim().isNotEmpty;
});
}
}
Future _verifyAccount(MailHoster mailHoster) async {
// password and possibly manual account details have been specified
setState(() {
_isAccountVerifying = true;
});
final mailAccount = MailAccount.fromDiscoveredSettings(
name: _emailController.text,
userName: _emailController.text,
email: _emailController.text,
password: _passwordController.text,
config: mailHoster.clientConfig,
);
final connectedAccount = await ref.read(
firstTimeMailClientSourceProvider(
account: RealAccount(mailAccount),
).future,
);
_mailClient = connectedAccount?.mailClient;
final isVerified = _mailClient?.isConnected ?? false;
if (connectedAccount != null && isVerified) {
final extensions = await AppExtension.loadFor(mailAccount);
_realAccount = connectedAccount.copyWith(appExtensions: extensions);
} else {
FocusManager.instance.primaryFocus?.unfocus();
}
setState(() {
_isAccountVerifying = false;
_isAccountVerified = isVerified;
_isContinueAvailable =
isVerified && _userNameController.text.trim().isNotEmpty;
});
}
Future _finalizeAccount() async {
final account = _realAccount;
final mailClient = _mailClient;
if (account == null || mailClient == null) {
if (kDebugMode) {
print('No account or mail client available');
}
return;
}
// Account name has been specified
account
..name = _accountNameController.text.trim()
..userName = _userNameController.text.trim();
ref.read(realAccountsProvider.notifier).addAccount(account);
if (PlatformInfo.isCupertino) {
context.goNamed(Routes.appDrawer);
unawaited(
context.pushNamed(
Routes.mailForAccount,
pathParameters: {Routes.pathParameterEmail: account.key},
),
);
} else {
context.pushReplacementNamed(
Routes.mailForAccount,
pathParameters: {Routes.pathParameterEmail: account.key},
);
}
}
Step _buildEmailStep(BuildContext context, AppLocalizations localizations) =>
Step(
title: _currentStep == 0
? Text(localizations.addAccountEmailLabel)
: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(localizations.addAccountEmailLabel),
Text(
_emailController.text,
style: Theme.of(context).textTheme.bodySmall,
),
],
),
content: Column(
children: [
DecoratedPlatformTextField(
autocorrect: false,
controller: _emailController,
keyboardType: TextInputType.emailAddress,
cupertinoShowLabel: false,
onChanged: (value) {
final isValid = Validator.validateEmail(value);
final account = _realAccount;
if (isValid && account != null) {
account.email = value;
}
if (isValid != _isContinueAvailable) {
setState(() {
_isContinueAvailable = isValid;
});
}
},
decoration: InputDecoration(
labelText: localizations.addAccountEmailLabel,
hintText: localizations.addAccountEmailHint,
icon: const Icon(Icons.email),
),
autofocus: true,
onSubmitted: (value) {
if (_isContinueAvailable) {
_onStepProgressed(1);
}
},
),
],
),
//state: StepState.editing,
isActive: true,
);
Step _buildPasswordStep(
BuildContext context,
AppLocalizations localizations,
) {
final mailHoster = _mailHoster;
final oauthClient = mailHoster?.oauthClient;
final appSpecificPasswordSetupUrl = mailHoster?.appSpecificPasswordSetupUrl;
final extensionForgotPassword = _extensionForgotPassword;
return Step(
title: Text(localizations.addAccountPasswordLabel),
//state: StepState.complete,
isActive: _currentStep >= 1,
content: Column(
children: [
if (_isProviderResolving)
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
child: const PlatformProgressIndicator(),
),
Expanded(
child: Text(
localizations.addAccountResolvingSettingsLabel(
_emailController.text,
),
),
),
],
)
else if (mailHoster != null)
_buildPasswordStepWithMailHoster(
oauthClient,
localizations,
mailHoster,
context,
appSpecificPasswordSetupUrl,
extensionForgotPassword,
)
else
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
localizations.addAccountResolvingSettingsFailedInfo(
_emailController.text,
),
),
PlatformElevatedButton(
child: Text(localizations.addAccountEditManuallyAction),
onPressed: () =>
_navigateToManualSettings(context, localizations),
),
],
),
],
),
);
}
Column _buildPasswordStepWithMailHoster(
OauthClient? oauthClient,
AppLocalizations localizations,
MailHoster mailHoster,
BuildContext context,
String? appSpecificPasswordSetupUrl,
AppExtensionActionDescription? extensionForgotPassword,
) =>
Column(
children: [
if (oauthClient != null)
..._buildOauthAuthenticationSection(
localizations,
mailHoster,
context,
oauthClient,
appSpecificPasswordSetupUrl,
)
else if (mailHoster.appSpecificPasswordSetupUrl != null)
..._buildAppSpecificPasswordSection(localizations, mailHoster),
if (mailHoster.appSpecificPasswordSetupUrl == null ||
(_isApplicationSpecificPasswordAcknowledged ?? false))
PasswordField(
controller: _passwordController,
cupertinoShowLabel: false,
onChanged: (value) {
final bool isValid = value.isNotEmpty &&
(_mailHoster?.clientConfig != null || _isManualSettings);
if (isValid != _isContinueAvailable) {
setState(() {
_isContinueAvailable = isValid;
});
}
},
autofocus: true,
labelText: localizations.addAccountPasswordLabel,
hintText: localizations.addAccountPasswordHint,
onSubmitted: (value) {
if (_isContinueAvailable) {
_onStepProgressed(2);
}
},
),
PlatformTextButton(
onPressed: () => _navigateToManualSettings(context, localizations),
child: Text(
localizations.addAccountResolvedSettingsWrongAction(
_mailHoster?.displayName ?? '<unknown>',
),
),
),
if (extensionForgotPassword != null)
PlatformTextButton(
onPressed: () {
final languageCode = localizations.localeName;
final url = (extensionForgotPassword.action?.url ?? '')
.replaceAll('{user.email}', _emailController.text)
.replaceAll('{language}', languageCode);
launcher.launchUrl(Uri.parse(url));
},
child: Text(
extensionForgotPassword.getLabel(localizations.localeName) ??
'',
),
),
],
);
List<Widget> _buildAppSpecificPasswordSection(
AppLocalizations localizations,
MailHoster mailHoster,
) =>
[
Text(localizations.addAccountApplicationPasswordRequiredInfo),
PlatformTextButton(
onPressed: () async {
await launcher.launchUrl(
Uri.parse(mailHoster.appSpecificPasswordSetupUrl ?? ''),
);
},
child: Text(
localizations.addAccountApplicationPasswordRequiredButton,
),
),
PlatformCheckboxListTile(
onChanged: (value) => setState(
() => _isApplicationSpecificPasswordAcknowledged = value,
),
value: _isApplicationSpecificPasswordAcknowledged,
title: Text(
localizations.addAccountApplicationPasswordRequiredAcknowledged,
),
),
];
List<Widget> _buildOauthAuthenticationSection(
AppLocalizations localizations,
MailHoster mailHoster,
BuildContext context,
OauthClient oauthClient,
String? appSpecificPasswordSetupUrl,
) =>
[
// The user can continue to sign in with the provider
// or by using an app-specific password
Text(
localizations.addAccountOauthOptionsText(
mailHoster.displayName ?? '<unknown>',
),
),
FittedBox(
child: mailHoster.buildSignInButton(
ref,
onPressed: () => _loginWithOAuth(
mailHoster,
oauthClient,
_emailController.text,
),
isSignInButton: true,
),
),
if (appSpecificPasswordSetupUrl != null) ...[
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
localizations.addAccountOauthSignInWithAppPassword,
),
),
PlatformTextButton(
onPressed: () async {
await launcher.launchUrl(Uri.parse(appSpecificPasswordSetupUrl));
},
child: Text(
localizations.addAccountApplicationPasswordRequiredButton,
),
),
PlatformCheckboxListTile(
onChanged: (value) => setState(
() => _isApplicationSpecificPasswordAcknowledged = value,
),
value: _isApplicationSpecificPasswordAcknowledged,
title: Text(
localizations.addAccountApplicationPasswordRequiredAcknowledged,
),
),
],
];
Step _buildAccountSetupStep(
BuildContext context,
AppLocalizations localizations,
) =>
Step(
title: Text(_isAccountVerified
? localizations.addAccountSetupAccountStep
: localizations.addAccountVerificationStep),
content: Column(
children: [
if (_isAccountVerifying)
Row(
children: [
Container(
padding: const EdgeInsets.all(8),
child: const PlatformProgressIndicator(),
),
Expanded(
child: Text(
localizations.addAccountVerifyingSettingsLabel(
_emailController.text,
),
),
),
],
)
else if (_isAccountVerified)
..._buildAccountVerifiedSection(localizations)
else
..._buildAccountVerificationFailedSection(localizations),
],
),
);
List<Widget> _buildAccountVerificationFailedSection(
AppLocalizations localizations,
) =>
[
Text(
localizations.addAccountVerifyingFailedInfo(
_emailController.text,
),
),
if (_mailHoster?.manualImapAccessSetupUrl != null) ...[
Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Text(
localizations.accountAddImapAccessSetupMightBeRequired,
),
),
PlatformTextButton(
child: Text(
localizations.addAccountSetupImapAccessButtonLabel,
),
onPressed: () => launcher.launchUrl(
Uri.parse(_mailHoster?.manualImapAccessSetupUrl ?? ''),
),
),
],
];
List<Widget> _buildAccountVerifiedSection(AppLocalizations localizations) => [
Text(
localizations.addAccountVerifyingSuccessInfo(
_emailController.text,
),
),
DecoratedPlatformTextField(
controller: _userNameController,
keyboardType: TextInputType.text,
textCapitalization: TextCapitalization.words,
onChanged: (value) {
final bool isValid = value.trim().isNotEmpty &&
_accountNameController.text.trim().isNotEmpty;
if (isValid != _isContinueAvailable) {
setState(() {
_isContinueAvailable = isValid;
});
}
},
decoration: InputDecoration(
labelText: localizations.addAccountNameOfUserLabel,
hintText: localizations.addAccountNameOfUserHint,
icon: const Icon(Icons.account_circle),
),
autofocus: true,
cupertinoAlignLabelOnTop: true,
onSubmitted: (_) => _accountNameNode.requestFocus(),
),
DecoratedPlatformTextField(
focusNode: _accountNameNode,
controller: _accountNameController,
keyboardType: TextInputType.text,
onChanged: (value) {
final bool isValid =
value.isNotEmpty && _userNameController.text.trim().isNotEmpty;
if (isValid != _isContinueAvailable) {
setState(() {
_isContinueAvailable = isValid;
});
}
},
decoration: InputDecoration(
labelText: localizations.addAccountNameOfAccountLabel,
hintText: localizations.addAccountNameOfAccountHint,
icon: const Icon(Icons.email),
),
cupertinoAlignLabelOnTop: true,
onSubmitted: (_) {
if (_isContinueAvailable) {
_onStepProgressed(3);
}
},
),
];
void _onMailHosterChanged(MailHoster provider, String email) {
final email = _emailController.text.trim();
final mailAccount = MailAccount.fromDiscoveredSettings(
name: email,
email: email,
userName: email,
password: _passwordController.text,
config: provider.clientConfig,
);
final realAccount = RealAccount(mailAccount);
_realAccount = realAccount;
AppExtension.loadFor(mailAccount).then((value) {
realAccount.appExtensions = value;
final forgotPwUrl = realAccount.appExtensionForgotPassword;
if (forgotPwUrl != null) {
setState(() {
_extensionForgotPassword = forgotPwUrl;
});
}
});
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/mail_screen_for_default_account.dart
|
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/provider.dart';
import 'screens.dart';
/// Shows the inbox of the default account
class MailScreenForDefaultAccount extends ConsumerWidget {
/// Creates a [MailScreenForDefaultAccount]
const MailScreenForDefaultAccount({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final accounts = ref.watch(allAccountsProvider);
if (accounts.isEmpty) {
return const WelcomeScreen();
}
final account = accounts.first;
return MailScreen(
account: account,
showSplashWhileLoading: true,
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/error_screen.dart
|
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../localization/extension.dart';
import '../logger.dart';
import 'base.dart';
/// Displays details about an error
class ErrorScreen extends ConsumerWidget {
/// Creates an [ErrorScreen]
ErrorScreen({
super.key,
required this.error,
this.stackTrace,
this.message,
}) {
logger.e(
'${message ?? 'ErrorScreen'}: $error',
error: error,
stackTrace: stackTrace ?? StackTrace.current,
);
}
/// The error
final Object error;
/// The optional error message
final String? message;
/// The optional stack trace
final StackTrace? stackTrace;
@override
Widget build(BuildContext context, WidgetRef ref) => BasePage(
title: ref.text.errorTitle,
content: Center(
child: Padding(
padding: const EdgeInsets.all(8),
child: SelectableText(message ?? '$error'),
),
),
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/webview_screen.dart
|
import 'package:enough_mail_flutter/enough_mail_flutter.dart' as webview;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import '../models/web_view_configuration.dart';
import 'base.dart';
// import '../l10n/app_localizations.g.dart';
class WebViewScreen extends StatelessWidget {
const WebViewScreen({super.key, required this.configuration});
final WebViewConfiguration configuration;
@override
Widget build(BuildContext context) => BasePage(
title: configuration.title ?? configuration.uri.host,
content: SafeArea(
child: webview.InAppWebView(
initialUrlRequest: webview.URLRequest(
url: webview.WebUri.uri(configuration.uri),
),
),
),
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/screens.dart
|
export '../location/view.dart';
export '../lock/view.dart';
export 'account_add_screen.dart';
export 'account_edit_screen.dart';
export 'account_server_details_screen.dart';
export 'compose_screen.dart';
export 'email_screen.dart';
export 'mail_screen.dart';
export 'mail_screen_for_default_account.dart';
export 'mail_search_screen.dart';
export 'media_screen.dart';
export 'message_details_screen.dart';
export 'message_details_screen_for_notification.dart';
export 'message_source_screen.dart';
export 'sourcecode_screen.dart';
export 'splash_screen.dart';
export 'webview_screen.dart';
export 'welcome_screen.dart';
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/media_screen.dart
|
import 'dart:async';
import 'dart:convert';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_media/enough_media.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:share_plus/share_plus.dart';
import '../account/model.dart';
import '../account/provider.dart';
import '../localization/extension.dart';
import '../models/compose_data.dart';
import '../models/message.dart';
import '../models/message_source.dart';
import '../routes/routes.dart';
import '../settings/provider.dart';
import '../settings/theme/icon_service.dart';
import '../util/localized_dialog_helper.dart';
import 'base.dart';
enum _OverflowMenuChoice {
showAsEmail,
}
class InteractiveMediaScreen extends ConsumerWidget {
const InteractiveMediaScreen({super.key, required this.mediaWidget});
final InteractiveMediaWidget mediaWidget;
@override
Widget build(BuildContext context, WidgetRef ref) {
final localizations = ref.text;
final iconService = IconService.instance;
return BasePage(
title: mediaWidget.mediaProvider.name,
content: mediaWidget,
appBarActions: [
DensePlatformIconButton(
icon: Icon(iconService.messageActionForward),
onPressed: () => _forward(context),
),
DensePlatformIconButton(
icon: Icon(iconService.share),
onPressed: _share,
),
if (mediaWidget.mediaProvider.isText &&
ref.read(settingsProvider).enableDeveloperMode)
PlatformPopupMenuButton<_OverflowMenuChoice>(
onSelected: (_OverflowMenuChoice result) async {
switch (result) {
case _OverflowMenuChoice.showAsEmail:
final provider = mediaWidget.mediaProvider;
var showErrorMessage = true;
try {
MimeMessage? mime;
if (provider is TextMediaProvider) {
mime = MimeMessage.parseFromText(provider.text);
} else if (provider is MemoryMediaProvider) {
mime = MimeMessage.parseFromData(provider.data);
}
if (mime != null) {
final account = ref.read(currentAccountProvider);
if (account is RealAccount) {
final source = SingleMessageSource(
null,
account: account,
);
final message = Message(mime, source, 0)
..isEmbedded = true;
source.singleMessage = message;
showErrorMessage = false;
unawaited(
context.pushNamed(Routes.mailDetails, extra: message),
);
}
}
} catch (e, s) {
if (kDebugMode) {
print('Unable to convert text into mime: $e $s');
}
}
if (showErrorMessage) {
if (context.mounted) {
await LocalizedDialogHelper.showTextDialog(
ref,
localizations.errorTitle,
localizations.developerShowAsEmailFailed,
);
}
}
break;
}
},
itemBuilder: (BuildContext context) => [
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.showAsEmail,
child: Text(localizations.developerShowAsEmail),
),
],
),
],
);
}
void _forward(BuildContext context) {
final provider = mediaWidget.mediaProvider;
final messageBuilder = MessageBuilder()..subject = provider.name;
if (provider is TextMediaProvider) {
messageBuilder.addBinary(
utf8.encode(provider.text),
MediaType.fromText(provider.mediaType),
filename: provider.name,
);
} else if (provider is MemoryMediaProvider) {
messageBuilder.addBinary(
provider.data,
MediaType.fromText(provider.mediaType),
filename: provider.name,
);
}
final composeData =
ComposeData(null, messageBuilder, ComposeAction.newMessage);
context.pushNamed(Routes.mailCompose, extra: composeData);
}
void _share() {
final provider = mediaWidget.mediaProvider;
share(provider);
}
static Future share(MediaProvider provider) {
if (provider is TextMediaProvider) {
return _shareText(provider);
} else if (provider is MemoryMediaProvider) {
return _shareFile(provider);
} else {
if (kDebugMode) {
print('Unable to share media provider $provider');
}
return Future.value();
}
}
static Future _shareText(TextMediaProvider provider) => Share.share(
provider.text,
subject: provider.description ?? provider.name,
);
static Future _shareFile(MemoryMediaProvider provider) async {
final file = XFile.fromData(
provider.data,
mimeType: provider.mediaType,
name: provider.name,
);
await Share.shareXFiles(
[file],
subject: provider.name,
text: provider.description,
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/message_source_screen.dart
|
import 'dart:async';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/provider.dart';
import '../localization/app_localizations.g.dart';
import '../localization/extension.dart';
import '../logger.dart';
import '../mail/model.dart';
import '../models/compose_data.dart';
import '../models/date_sectioned_message_source.dart';
import '../models/message.dart';
import '../models/message_source.dart';
import '../models/swipe.dart';
import '../notification/service.dart';
import '../routes/routes.dart';
import '../scaffold_messenger/service.dart';
import '../settings/provider.dart';
import '../settings/theme/icon_service.dart';
import '../util/localized_dialog_helper.dart';
import '../util/string_helper.dart';
import '../widgets/search_text_field.dart';
import '../widgets/widgets.dart';
import 'base.dart';
enum _Visualization { stack, list }
/// Displays a list of mails
class MessageSourceScreen extends ConsumerStatefulWidget {
/// Creates a new [MessageSourceScreen]
const MessageSourceScreen({
super.key,
required this.messageSource,
});
/// The source for the shown messages
final MessageSource messageSource;
@override
ConsumerState<MessageSourceScreen> createState() =>
_MessageSourceScreenState();
}
class _MessageSourceScreenState extends ConsumerState<MessageSourceScreen>
with TickerProviderStateMixin {
late Future<void> _messageLoader;
_Visualization _visualization = _Visualization.list;
late DateSectionedMessageSource _sectionedMessageSource;
bool _isInSelectionMode = false;
List<Message> _selectedMessages = [];
bool _isInSearchMode = false;
bool _hasSearchInput = false;
late TextEditingController _searchEditingController;
@override
void initState() {
super.initState();
_searchEditingController = TextEditingController();
_sectionedMessageSource = DateSectionedMessageSource(
widget.messageSource,
firstDayOfWeek: ref.firstDayOfWeek,
);
_sectionedMessageSource.addListener(_update);
_messageLoader = _initMessageSource();
}
Future<void> _initMessageSource() => _sectionedMessageSource.init();
@override
void dispose() {
_searchEditingController.dispose();
_sectionedMessageSource
..removeListener(_update)
..dispose();
super.dispose();
}
void _update() {
setState(() {});
}
void _search(String query) {
final trimmedQuery = query.trim();
if (trimmedQuery.isEmpty) {
setState(() {
_isInSearchMode = false;
});
return;
}
final search = MailSearch(trimmedQuery, SearchQueryType.allTextHeaders);
final searchSource =
_sectionedMessageSource.messageSource.search(ref.text, search);
context.pushNamed(
Routes.messageSource,
pathParameters: {
Routes.pathParameterEmail: widget.messageSource.account.email,
},
extra: searchSource,
);
setState(() {
_isInSearchMode = false;
});
}
@override
Widget build(BuildContext context) {
// print('parent name: ${widget.messageSource.parentName}');
final settings = ref.watch(settingsProvider);
final theme = Theme.of(context);
final localizations = ref.text;
final source = _sectionedMessageSource.messageSource;
final searchColor = theme.brightness == Brightness.light
? theme.colorScheme.onSecondary
: theme.colorScheme.onPrimary;
final appBarTitle = _isInSearchMode
? TextField(
cursorColor: searchColor,
controller: _searchEditingController,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: localizations.homeSearchHint,
hintStyle: TextStyle(
color: searchColor.withAlpha(0xa0),
),
),
autofocus: true,
autocorrect: false,
style: TextStyle(
color: searchColor,
),
onSubmitted: _search,
onChanged: (text) {
if (text.isNotEmpty != _hasSearchInput) {
setState(() {
_hasSearchInput = text.isNotEmpty;
});
}
},
)
: (PlatformInfo.isCupertino)
? Text(source.localizedName(localizations, settings))
: BaseTitle(
title: source.localizedName(localizations, settings),
subtitle: source.description,
);
final appBarActions = [
if (_isInSearchMode && _hasSearchInput)
IconButton(
icon: Icon(CommonPlatformIcons.clear),
onPressed: () {
_searchEditingController.text = '';
setState(() {
_hasSearchInput = false;
});
},
),
if (source.supportsSearching && !PlatformInfo.isCupertino)
PlatformIconButton(
icon: Icon(_isInSearchMode ? Icons.arrow_back : Icons.search),
onPressed: () {
if (_isInSearchMode) {
setState(() {
_isInSearchMode = false;
});
} else {
setState(() {
_isInSearchMode = true;
});
}
},
),
if (PlatformInfo.isCupertino)
CupertinoButton(
padding: EdgeInsets.zero,
child: Text(
_isInSelectionMode
? localizations.actionCancel
: localizations.actionEdit,
),
onPressed: () {
setState(() {
_isInSelectionMode = !_isInSelectionMode;
});
},
),
// if (!_isInSearchMode)
// PlatformPopupMenuButton<_Visualization>(
// onSelected: switchVisualization,
// itemBuilder: (context) => [
// _visualization == _Visualization.list
// ? PlatformPopupMenuItem<_Visualization>(
// value: _Visualization.stack,
// child: Text(localizations.homeActionsShowAsStack),
// )
// : PlatformPopupMenuItem<_Visualization>(
// value: _Visualization.list,
// child: Text(localizations.homeActionsShowAsList),
// ),
// ],
// ),
];
Widget? zeroPosWidget;
if (_sectionedMessageSource.isInitialized && source.size == 0) {
final emptyMessage = source.isSearch
? localizations.homeEmptySearchMessage
: localizations.homeEmptyFolderMessage;
zeroPosWidget = Padding(
padding: const EdgeInsets.symmetric(vertical: 32, horizontal: 32),
child: Text(emptyMessage),
);
} else if (source.supportsDeleteAll) {
final iconService = IconService.instance;
final style = TextButton.styleFrom(foregroundColor: Colors.grey[600]);
final textStyle = Theme.of(context).textTheme.labelLarge;
zeroPosWidget = Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: Wrap(
children: [
PlatformTextButtonIcon(
style: style,
icon: Icon(iconService.messageActionDelete),
label: Text(localizations.homeDeleteAllAction, style: textStyle),
onPressed: _deleteAllMessages,
),
PlatformTextButtonIcon(
style: style,
icon: Icon(iconService.messageIsSeen),
label:
Text(localizations.homeMarkAllSeenAction, style: textStyle),
onPressed: () async {
await source.markAllMessagesSeen(true);
},
),
PlatformTextButtonIcon(
style: style,
icon: Icon(iconService.messageIsNotSeen),
label:
Text(localizations.homeMarkAllUnseenAction, style: textStyle),
onPressed: () async {
await source.markAllMessagesSeen(false);
},
),
],
),
);
}
final isSentFolder = source.isSent;
final showSearchTextField =
PlatformInfo.isCupertino && source.supportsSearching;
final hasAccountWithError = ref.watch(hasAccountWithErrorProvider);
return PlatformPageScaffold(
bottomBar: _isInSelectionMode
? buildSelectionModeBottomBar(localizations)
: PlatformInfo.isCupertino
? CupertinoStatusBar(
info: CupertinoStatusBar.createInfo(source.description),
rightAction: PlatformIconButton(
// TODO(RV): use CupertinoIcons.create once available
icon: const Icon(CupertinoIcons.pen),
onPressed: () => context.pushNamed(
Routes.mailCompose,
extra: ComposeData(
null,
MessageBuilder(),
ComposeAction.newMessage,
),
),
),
)
: null,
material: (context, platform) => MaterialScaffoldData(
drawer: const AppDrawer(),
floatingActionButton: _visualization == _Visualization.stack
? null
: const NewMailMessageButton(),
),
// cupertino: (context, platform) => CupertinoPageScaffoldData(),
appBar: (_visualization == _Visualization.stack)
? PlatformAppBar(
title: appBarTitle,
trailingActions: appBarActions,
leading: hasAccountWithError ? const MenuWithBadge() : null,
)
: null,
body: FutureBuilder<void>(
future: _messageLoader,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
return Center(
child: Row(
children: [
const Padding(
padding: EdgeInsets.all(8),
child: PlatformProgressIndicator(),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: Text(
localizations.homeLoading(
source.name ?? source.description ?? '',
),
),
),
),
],
),
);
case ConnectionState.done:
if (_visualization == _Visualization.stack) {
return WillPopScope(
onWillPop: () {
switchVisualization(_Visualization.list);
return Future.value(false);
},
child: MessageStack(messageSource: source),
);
}
final settings = ref.read(settingsProvider);
final swipeLeftToRightAction = settings.swipeLeftToRightAction;
final swipeRightToLeftAction = settings.swipeRightToLeftAction;
return WillPopScope(
onWillPop: () {
if (_isInSelectionMode) {
leaveSelectionMode();
return Future.value(false);
}
return Future.value(true);
},
child: RefreshIndicator(
onRefresh: () async {
await _sectionedMessageSource.refresh();
},
child: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: [
EnoughPlatformSliverAppBar(
stretch: true,
title: appBarTitle,
leading: hasAccountWithError
? MenuWithBadge(
iOSText:
'\u2329 ${localizations.accountsTitle}',
)
: null,
previousPageTitle:
source.parentName ?? localizations.accountsTitle,
floating: !_isInSearchMode,
pinned: _isInSearchMode,
actions: appBarActions,
cupertinoTransitionBetweenRoutes: true,
),
if (showSearchTextField)
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
child: CupertinoSearch(
messageSource: source,
),
),
),
if (zeroPosWidget != null)
SliverToBoxAdapter(
child: zeroPosWidget,
),
SliverFixedExtentList.builder(
itemExtent: 52,
itemBuilder: (context, index) =>
FutureBuilder<SectionElement>(
future: _sectionedMessageSource.getElementAt(index),
initialData:
_sectionedMessageSource.getCachedElementAt(index),
builder: (context, snapshot) {
if (snapshot.hasError) {
return PlatformListTile(
title: const Row(
children: [
Icon(Icons.replay),
// TODO(RV): localize reload
Text(' reload'),
],
),
onTap: () {
// TODO(RV): implement reload
setState(() {});
},
);
}
final element = snapshot.data;
if (element == null) {
return const EmptyMessage();
}
final section = element.section;
if (section != null) {
final text = ref.getDateRangeName(
section.range,
);
return GestureDetector(
onLongPress: () async {
_selectedMessages =
await _sectionedMessageSource
.getMessagesForSection(section);
for (final m in _selectedMessages) {
m.isSelected = true;
}
setState(() {
_isInSelectionMode = true;
});
},
onTap: !_isInSelectionMode
? null
: () async {
final sectionMessages =
await _sectionedMessageSource
.getMessagesForSection(
section,
);
final doSelect =
!sectionMessages.first.isSelected;
for (final msg in sectionMessages) {
if (doSelect) {
if (!msg.isSelected) {
msg.isSelected = true;
_selectedMessages.add(msg);
}
} else {
if (msg.isSelected) {
msg.isSelected = false;
_selectedMessages.remove(msg);
}
}
}
setState(() {});
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(
left: 16,
right: 8,
bottom: 4,
top: 16,
),
child: Text(
text,
style: TextStyle(
color: theme.colorScheme.secondary,
),
),
),
const Divider(),
],
),
);
}
final message = element.message;
if (message == null) {
return const SizedBox.shrink();
}
return Dismissible(
key: ValueKey(message),
dismissThresholds: {
DismissDirection.startToEnd:
swipeLeftToRightAction.dismissThreshold,
DismissDirection.endToStart:
swipeRightToLeftAction.dismissThreshold,
},
background: Container(
color: swipeLeftToRightAction.colorBackground,
padding: const EdgeInsets.symmetric(
horizontal: 8,
),
alignment: AlignmentDirectional.centerStart,
child: Row(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
),
child: Text(
swipeLeftToRightAction
.name(localizations),
style: TextStyle(
color: swipeLeftToRightAction
.colorForeground,
),
),
),
Icon(
swipeLeftToRightAction.icon,
color: swipeLeftToRightAction.colorIcon,
),
],
),
),
secondaryBackground: Container(
color: swipeRightToLeftAction.colorBackground,
padding: const EdgeInsets.symmetric(
horizontal: 8,
),
alignment: AlignmentDirectional.centerEnd,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Icon(
swipeRightToLeftAction.icon,
color: swipeRightToLeftAction.colorIcon,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8,
),
child: Text(
swipeRightToLeftAction
.name(localizations),
style: TextStyle(
color: swipeRightToLeftAction
.colorForeground,
),
),
),
],
),
),
child: MessageOverview(
message,
_isInSelectionMode,
onMessageTap,
onMessageLongPress,
isSentMessage: isSentFolder,
),
confirmDismiss: (direction) {
final swipeAction =
direction == DismissDirection.startToEnd
? swipeLeftToRightAction
: swipeRightToLeftAction;
fireSwipeAction(
localizations,
swipeAction,
message,
);
return Future.value(
swipeAction.isMessageMoving,
);
},
);
},
),
itemCount: _sectionedMessageSource.size,
),
],
),
),
);
}
},
),
);
}
Widget buildSelectionModeBottomBar(AppLocalizations localizations) {
final source = _sectionedMessageSource.messageSource;
final isTrash = source.isTrash;
final isJunk = source.isJunk;
final isAnyUnseen = _selectedMessages.any((m) => !m.isSeen);
final isAnyUnflagged = _selectedMessages.any((m) => !m.isFlagged);
final iconService = IconService.instance;
return PlatformBottomBar(
cupertinoBlurBackground: true,
child: SafeArea(
top: false,
child: Row(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Text('${_selectedMessages.length}'),
),
if (isAnyUnseen)
PlatformIconButton(
icon: Icon(iconService.messageIsNotSeen),
onPressed: () => _handleMultipleChoice(_MultipleChoice.seen),
)
else
PlatformIconButton(
icon: Icon(iconService.messageIsSeen),
onPressed: () => _handleMultipleChoice(_MultipleChoice.unseen),
),
if (isAnyUnflagged)
PlatformIconButton(
icon: Icon(iconService.messageIsNotFlagged),
onPressed: () => _handleMultipleChoice(_MultipleChoice.flag),
)
else
PlatformIconButton(
icon: Icon(iconService.messageIsFlagged),
onPressed: () => _handleMultipleChoice(_MultipleChoice.unflag),
),
if (isJunk)
PlatformIconButton(
icon: Icon(iconService.messageActionMoveFromJunkToInbox),
onPressed: () => _handleMultipleChoice(_MultipleChoice.inbox),
)
else
PlatformIconButton(
icon: Icon(iconService.messageActionMoveToJunk),
onPressed: () => _handleMultipleChoice(_MultipleChoice.junk),
),
const Spacer(),
if (isTrash)
PlatformIconButton(
icon: Icon(iconService.messageActionMoveToInbox),
onPressed: () => _handleMultipleChoice(_MultipleChoice.inbox),
)
else
PlatformIconButton(
icon: Icon(iconService.messageActionDelete),
onPressed: () => _handleMultipleChoice(_MultipleChoice.delete),
),
PlatformIconButton(
icon: const Icon(Icons.close),
onPressed: leaveSelectionMode,
),
PlatformPopupMenuButton<_MultipleChoice>(
onSelected: _handleMultipleChoice,
itemBuilder: (context) => [
PlatformPopupMenuItem(
value: _MultipleChoice.forwardAsAttachment,
child: IconText(
icon: Icon(iconService.messageActionForwardAsAttachment),
label: Text(localizations.messageActionForwardAsAttachment),
),
),
PlatformPopupMenuItem(
value: _MultipleChoice.forwardAttachments,
child: IconText(
icon: Icon(iconService.messageActionForwardAttachments),
label: Text(localizations.messagesActionForwardAttachments),
),
),
if (isTrash)
PlatformPopupMenuItem(
value: _MultipleChoice.inbox,
child: IconText(
icon: Icon(iconService.messageActionMoveToInbox),
label: Text(localizations.messageActionMoveToInbox),
),
)
else
PlatformPopupMenuItem(
value: _MultipleChoice.delete,
child: IconText(
icon: Icon(iconService.messageActionDelete),
label: Text(localizations.messageActionDelete),
),
),
const PlatformPopupDivider(),
if (isAnyUnseen)
PlatformPopupMenuItem(
value: _MultipleChoice.seen,
child: IconText(
icon: Icon(iconService.messageIsSeen),
label: Text(localizations.messageActionMultipleMarkSeen),
),
)
else
PlatformPopupMenuItem(
value: _MultipleChoice.unseen,
child: IconText(
icon: Icon(iconService.messageIsNotSeen),
label:
Text(localizations.messageActionMultipleMarkUnseen),
),
),
if (isAnyUnflagged)
PlatformPopupMenuItem(
value: _MultipleChoice.flag,
child: IconText(
icon: Icon(iconService.messageIsFlagged),
label:
Text(localizations.messageActionMultipleMarkFlagged),
),
)
else
PlatformPopupMenuItem(
value: _MultipleChoice.unflag,
child: IconText(
icon: Icon(iconService.messageIsNotFlagged),
label: Text(
localizations.messageActionMultipleMarkUnflagged,
),
),
),
if (source.supportsMessageFolders) ...[
const PlatformPopupDivider(),
PlatformPopupMenuItem(
value: _MultipleChoice.move,
child: IconText(
icon: Icon(iconService.messageActionMove),
label: Text(localizations.messageActionMove),
),
),
if (isJunk)
PlatformPopupMenuItem(
value: _MultipleChoice.inbox,
child: IconText(
icon:
Icon(iconService.messageActionMoveFromJunkToInbox),
label: Text(localizations.messageActionMarkAsNotJunk),
),
)
else
PlatformPopupMenuItem(
value: _MultipleChoice.junk,
child: IconText(
icon: Icon(iconService.messageActionMoveToJunk),
label: Text(localizations.messageActionMarkAsJunk),
),
),
if (source.isArchive)
PlatformPopupMenuItem(
value: _MultipleChoice.inbox,
child: IconText(
icon: Icon(iconService.messageActionMoveToInbox),
label: Text(localizations.messageActionUnarchive),
),
)
else
PlatformPopupMenuItem(
value: _MultipleChoice.archive,
child: IconText(
icon: Icon(iconService.messageActionArchive),
label: Text(localizations.messageActionArchive),
),
),
], // folders are supported
if (_selectedMessages.length == 1)
PlatformPopupMenuItem(
value: _MultipleChoice.viewInSafeMode,
child: IconText(
icon: Icon(iconService.messageActionViewInSafeMode),
label: Text(localizations.messageActionViewInSafeMode),
),
),
PlatformPopupMenuItem(
value: _MultipleChoice.addNotification,
child: IconText(
icon: Icon(iconService.messageActionAddNotification),
label: Text(
localizations.messageActionAddNotification,
),
),
),
],
),
],
),
),
);
}
Future<void> _handleMultipleChoice(_MultipleChoice choice) async {
final source = _sectionedMessageSource.messageSource;
final localizations = ref.text;
if (_selectedMessages.isEmpty) {
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.multipleSelectionNeededInfo,
);
return;
}
try {
final endSelectionMode =
await _handleChoice(choice, source, localizations);
if (endSelectionMode) {
setState(() {
_isInSelectionMode = false;
});
}
} catch (e, s) {
logger.e(
'Unable to handle multiple choice $choice: $e',
error: e,
stackTrace: s,
);
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.multipleSelectionActionFailed(e.toString()),
);
}
}
Future<bool> _handleChoice(
_MultipleChoice choice,
MessageSource source,
AppLocalizations localizations,
) async {
var endSelectionMode = true;
switch (choice) {
case _MultipleChoice.forwardAsAttachment:
await forwardAsAttachments();
break;
case _MultipleChoice.forwardAttachments:
forwardAttachments();
break;
case _MultipleChoice.delete:
final notification =
localizations.multipleMovedToTrash(_selectedMessages.length);
await source.deleteMessages(
localizations,
_selectedMessages,
notification,
);
break;
case _MultipleChoice.inbox:
final notification =
localizations.multipleMovedToInbox(_selectedMessages.length);
await source.moveMessagesToFlag(
localizations,
_selectedMessages,
MailboxFlag.inbox,
notification,
);
break;
case _MultipleChoice.seen:
endSelectionMode = false;
await source.markMessagesAsSeen(_selectedMessages, true);
setState(() {});
break;
case _MultipleChoice.unseen:
endSelectionMode = false;
await source.markMessagesAsSeen(_selectedMessages, false);
setState(() {});
break;
case _MultipleChoice.flag:
endSelectionMode = false;
await source.markMessagesAsFlagged(_selectedMessages, true);
setState(() {});
break;
case _MultipleChoice.unflag:
endSelectionMode = false;
await source.markMessagesAsFlagged(_selectedMessages, false);
setState(() {});
break;
case _MultipleChoice.move:
endSelectionMode = false;
move();
break;
case _MultipleChoice.junk:
final notification =
localizations.multipleMovedToJunk(_selectedMessages.length);
await source.moveMessagesToFlag(
localizations,
_selectedMessages,
MailboxFlag.junk,
notification,
);
break;
case _MultipleChoice.archive:
final notification =
localizations.multipleMovedToArchive(_selectedMessages.length);
await source.moveMessagesToFlag(
localizations,
_selectedMessages,
MailboxFlag.archive,
notification,
);
break;
case _MultipleChoice.viewInSafeMode:
if (_selectedMessages.isNotEmpty && context.mounted) {
unawaited(context.pushNamed(
Routes.mailDetails,
extra: _selectedMessages.first,
queryParameters: {
Routes.queryParameterBlockExternalContent: 'true',
},
));
}
endSelectionMode = false;
leaveSelectionMode();
break;
case _MultipleChoice.addNotification:
endSelectionMode = false;
final notificationService = NotificationService.instance;
for (final message in _selectedMessages) {
await notificationService
.sendLocalNotificationForMailMessage(message);
}
leaveSelectionMode();
break;
}
return endSelectionMode;
}
Future<void> forwardAsAttachments() async {
await forwardAttachmentsLike(addMessageAttachment);
}
void forwardAttachments() {
forwardAttachmentsLike(addAttachments);
}
Future<void> forwardAttachmentsLike(
Future? Function(Message, MessageBuilder) loader,
) async {
final builder = MessageBuilder();
final fromAddresses = <MailAddress>[];
final subjects = <String>[];
final futures = <Future>[];
for (final message in _selectedMessages) {
message.isSelected = false;
final mailClient = message.source.getMimeSource(message)?.mailClient;
if (mailClient == null) {
continue;
}
final from = mailClient.account.fromAddress;
if (!fromAddresses.contains(from)) {
fromAddresses.add(from);
}
final mime = message.mimeMessage;
final subject = mime.decodeSubject();
if (subject != null && subject.isNotEmpty) {
subjects.add(subject.replaceAll('\r\n ', '').replaceAll('\n', ''));
}
final composeFuture = loader(message, builder);
if (composeFuture != null) {
futures.add(composeFuture);
}
}
if (fromAddresses.length == 1) {
builder.from = fromAddresses;
}
final lcs = StringHelper.largestCommonSequence(subjects);
// print('lcs for $subjects is "$lcs"');
if (lcs != null && lcs.length > 3) {
builder.subject = MessageBuilder.createForwardSubject(lcs);
}
final composeFuture = futures.isEmpty ? null : Future.wait(futures);
final composeData = ComposeData(
_selectedMessages,
builder,
ComposeAction.forward,
future: composeFuture,
);
unawaited(context.pushNamed(Routes.mailCompose, extra: composeData));
}
Future<void> addMessageAttachment(Message message, MessageBuilder builder) {
final mime = message.mimeMessage;
if (mime.mimeData == null) {
return message.source.fetchMessageContents(message).then((value) {
builder.addMessagePart(value);
});
} else {
builder.addMessagePart(mime);
}
return Future.value();
}
Future? addAttachments(Message message, MessageBuilder builder) {
final mime = message.mimeMessage;
Future? composeFuture;
if (mime.mimeData == null) {
composeFuture =
message.source.fetchMessageContents(message).then((value) {
for (final attachment in message.attachments) {
final part = value.getPart(attachment.fetchId);
builder.addPart(mimePart: part);
}
});
} else {
final futures = <Future>[];
for (final attachment in message.attachments) {
final part = mime.getPart(attachment.fetchId);
if (part != null) {
builder.addPart(mimePart: part);
} else {
futures.add(message.source
.fetchMessagePart(message, fetchId: attachment.fetchId)
.then((value) {
builder.addPart(mimePart: value);
}));
}
composeFuture = futures.isEmpty ? null : Future.wait(futures);
}
}
return composeFuture;
}
void move() {
final localizations = ref.text;
var account = widget.messageSource.account;
if (account.isVirtual) {
// check how many mail-clients are involved in the current selection
// to either show the mailboxes of the unified account
// or of the real account
final mailClients = <MailClient>[];
for (final message in _selectedMessages) {
final mailClient = message.source.getMimeSource(message)?.mailClient;
if (mailClient != null && !mailClients.contains(mailClient)) {
mailClients.add(mailClient);
}
}
if (mailClients.length == 1) {
// ok, all messages belong to one account:
final singleAccount = ref.read(
findRealAccountByEmailProvider(
email: mailClients.first.account.email,
),
);
if (singleAccount != null) {
account = singleAccount;
}
}
}
LocalizedDialogHelper.showWidgetDialog(
ref,
SingleChildScrollView(
child: MailboxTree(
account: account,
onSelected: moveTo,
),
),
title: localizations.multipleMoveTitle(_selectedMessages.length),
defaultActions: DialogActions.cancel,
);
}
Future<void> moveTo(Mailbox mailbox) async {
setState(() {
_isInSelectionMode = false;
});
context.pop(); // alert
final source = _sectionedMessageSource.messageSource;
final localizations = ref.text;
final account = widget.messageSource.account;
if (account.isVirtual) {
await source.moveMessagesToFlag(
localizations,
_selectedMessages,
mailbox.flags.first,
localizations.moveSuccess(mailbox.name),
);
} else {
await source.moveMessages(
localizations,
_selectedMessages,
mailbox,
localizations.moveSuccess(mailbox.name),
);
}
}
void switchVisualization(_Visualization result) {
setState(() {
_visualization = result;
});
}
Future<void> onMessageTap(Message message) async {
if (_isInSelectionMode) {
message.toggleSelected();
if (message.isSelected) {
_selectedMessages.add(message);
} else {
_selectedMessages.remove(message);
}
setState(() {});
} else {
if (message.mimeMessage.hasFlag(MessageFlags.draft)) {
// continue to edit message:
// first download message:
final mime = await message.source.fetchMessageContents(message);
//message.updateMime(mime);
final builder = MessageBuilder.prepareFromDraft(mime);
final data = ComposeData([message], builder, ComposeAction.newMessage);
if (mounted) {
unawaited(context.pushNamed(Routes.mailCompose, extra: data));
}
} else {
// move to mail details:
if (mounted) {
unawaited(context.pushNamed(Routes.mailDetails, extra: message));
}
}
}
}
void onMessageLongPress(Message message) {
message.isSelected = true;
_selectedMessages = [message];
setState(() {
_isInSelectionMode = true;
});
}
void leaveSelectionMode() {
for (final m in _selectedMessages) {
m.isSelected = false;
}
_selectedMessages = [];
setState(() {
_isInSelectionMode = false;
});
}
Future<void> fireSwipeAction(
AppLocalizations localizations,
SwipeAction action,
Message message,
) {
switch (action) {
case SwipeAction.markRead:
final isSeen = !message.isSeen;
message.isSeen = isSeen;
return _sectionedMessageSource.messageSource
.markAsSeen(message, isSeen);
case SwipeAction.archive:
return _sectionedMessageSource.messageSource
.archive(localizations, message);
case SwipeAction.markJunk:
return _sectionedMessageSource.messageSource
.markAsJunk(localizations, message);
case SwipeAction.delete:
return _sectionedMessageSource.deleteMessage(localizations, message);
case SwipeAction.flag:
final isFlagged = !message.isFlagged;
message.isFlagged = isFlagged;
return _sectionedMessageSource.messageSource.storeMessageFlags(
[message],
[MessageFlags.flagged],
action: isFlagged ? StoreAction.add : StoreAction.remove,
);
}
}
Future<void> _deleteAllMessages() async {
final localizations = ref.text;
final firstMessage = widget.messageSource.cache.first;
var expunge =
firstMessage?.mimeMessage.hasFlag(MessageFlags.deleted) ?? false;
final confirmed = await LocalizedDialogHelper.showWidgetDialog(
ref,
Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(localizations.homeDeleteAllQuestion),
CheckboxText(
initialValue: expunge,
onChanged: (value) => expunge = value,
text: localizations.homeDeleteAllScrubOption,
),
],
),
title: localizations.homeDeleteAllTitle,
actions: [
PlatformDialogActionText(
text: localizations.actionCancel,
onPressed: () => context.pop(false),
),
PlatformDialogActionText(
text: localizations.homeDeleteAllAction,
isDestructiveAction: true,
onPressed: () => context.pop(true),
),
],
);
if (confirmed == true) {
final results =
await widget.messageSource.deleteAllMessages(expunge: expunge);
Function()? undo;
if (!expunge && results.any((result) => result.canUndo)) {
undo = () async {
final futures = <Future>[];
for (final result in results) {
if (result.canUndo) {
futures.add(result.mailClient.undoDeleteMessages(result));
}
}
if (futures.isNotEmpty) {
await Future.wait(futures);
await _sectionedMessageSource.refresh();
}
};
}
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.homeDeleteAllSuccess,
undo: undo,
);
}
}
}
class CheckboxText extends StatefulWidget {
const CheckboxText({
super.key,
required this.initialValue,
required this.onChanged,
required this.text,
});
final bool initialValue;
final Function(bool value) onChanged;
final String text;
@override
State<CheckboxText> createState() => _CheckboxTextState();
}
class _CheckboxTextState extends State<CheckboxText> {
late bool _value;
@override
void initState() {
super.initState();
_value = widget.initialValue;
}
@override
Widget build(BuildContext context) => PlatformCheckboxListTile(
title: Text(widget.text),
value: _value,
onChanged: (value) {
widget.onChanged(value ?? false);
setState(() {
_value = value ?? false;
});
},
);
}
enum _MultipleChoice {
forwardAsAttachment,
forwardAttachments,
delete,
inbox,
seen,
unseen,
flag,
unflag,
move,
junk,
archive,
viewInSafeMode,
addNotification,
}
class MessageOverview extends StatefulWidget {
MessageOverview(
this.message,
this.isInSelectionMode,
this.onTap,
this.onLongPress, {
this.animationController,
required this.isSentMessage,
}) : super(key: ValueKey(message.sourceIndex));
final Message message;
final bool isInSelectionMode;
final void Function(Message message) onTap;
final void Function(Message message) onLongPress;
final AnimationController? animationController;
final bool isSentMessage;
@override
State<MessageOverview> createState() => _MessageOverviewState();
}
class _MessageOverviewState extends State<MessageOverview> {
_MessageOverviewState();
@override
void dispose() {
widget.message.removeListener(_update);
super.dispose();
}
void _update() {
setState(() {});
}
@override
void initState() {
widget.message.addListener(_update);
super.initState();
}
@override
Widget build(BuildContext context) => (widget.animationController != null)
? SizeTransition(
sizeFactor: CurvedAnimation(
parent: widget.animationController!,
curve: Curves.easeOut,
),
child: buildMessageOverview(),
)
: buildMessageOverview();
Widget buildMessageOverview() => widget.isInSelectionMode
? PlatformCheckboxListTile(
value: widget.message.isSelected,
selected: widget.message.isSelected,
title: MessageOverviewContent(
message: widget.message,
isSentMessage: widget.isSentMessage,
),
onChanged: (value) => widget.onTap(widget.message),
)
: SelectablePlatformListTile(
visualDensity: VisualDensity.compact,
title: MessageOverviewContent(
message: widget.message,
isSentMessage: widget.isSentMessage,
),
onTap: () => widget.onTap(widget.message),
onLongPress: () => widget.onLongPress(widget.message),
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/welcome_screen.dart
|
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:introduction_screen/introduction_screen.dart';
import 'package:shimmer_animation/shimmer_animation.dart';
import '../../enough_mail_app.dart';
import '../settings/theme/icon_service.dart';
import '../widgets/legalese.dart';
/// Displays a welcome screen
class WelcomeScreen extends ConsumerWidget {
/// Creates a [WelcomeScreen]
const WelcomeScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final localizations = ref.text;
final pages = _buildPages(context, localizations);
final defaultColor = ref.watch(defaultColorSeedProvider);
return Theme(
data: ThemeData(
brightness: Brightness.dark,
primarySwatch:
defaultColor is MaterialColor ? defaultColor : Colors.green,
),
child: SafeArea(
child: PlatformScaffold(
body: IntroductionScreen(
pages: pages,
done: Text(localizations.actionDone),
onDone: () {
context.goNamed(Routes.accountAdd);
},
next: Text(localizations.actionNext),
skip: Text(localizations.actionSkip),
showSkipButton: true,
),
),
),
); //Material App
}
List<PageViewModel> _buildPages(
BuildContext context,
AppLocalizations localizations,
) =>
[
PageViewModel(
title: localizations.welcomePanel1Title,
body: localizations.welcomePanel1Text,
image: Image.asset(
'assets/images/maily.png',
height: 200,
fit: BoxFit.cover,
package: 'enough_mail_app',
),
decoration: PageDecoration(pageColor: Colors.green[700]),
footer: _buildFooter(context, localizations),
),
PageViewModel(
title: localizations.welcomePanel2Title,
body: localizations.welcomePanel2Text,
image: Image.asset(
'assets/images/mailboxes.png',
height: 200,
fit: BoxFit.cover,
package: 'enough_mail_app',
),
decoration: const PageDecoration(pageColor: Color(0xff543226)),
footer: _buildFooter(context, localizations),
),
PageViewModel(
title: localizations.welcomePanel3Title,
body: localizations.welcomePanel3Text,
image: Image.asset(
'assets/images/swipe_press.png',
height: 200,
fit: BoxFit.cover,
package: 'enough_mail_app',
),
decoration: const PageDecoration(pageColor: Color(0xff761711)),
footer: _buildFooter(context, localizations),
),
PageViewModel(
title: localizations.welcomePanel4Title,
body: localizations.welcomePanel4Text,
image: Image.asset(
'assets/images/drawing.jpg',
height: 200,
fit: BoxFit.cover,
package: 'enough_mail_app',
),
footer: _buildFooter(context, localizations),
),
];
Widget _buildFooter(BuildContext context, AppLocalizations localizations) =>
Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Shimmer(
duration: const Duration(seconds: 4),
interval: const Duration(seconds: 6),
child: PlatformFilledButtonIcon(
icon: Icon(IconService.instance.email),
label: Center(
child: Text(localizations.welcomeActionSignIn),
),
onPressed: () {
context.goNamed(Routes.accountAdd);
},
),
),
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Legalese(),
),
],
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/message_details_screen.dart
|
import 'dart:async';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_mail_flutter/enough_mail_flutter.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
import '../localization/app_localizations.g.dart';
import '../localization/extension.dart';
import '../logger.dart';
import '../mail/provider.dart';
import '../models/compose_data.dart';
import '../models/message.dart';
import '../models/message_source.dart';
import '../notification/service.dart';
import '../routes/routes.dart';
import '../settings/model.dart';
import '../settings/provider.dart';
import '../settings/theme/icon_service.dart';
import '../util/localized_dialog_helper.dart';
import '../widgets/attachment_chip.dart';
import '../widgets/empty_message.dart';
import '../widgets/expansion_wrap.dart';
import '../widgets/ical_interactive_media.dart';
import '../widgets/mail_address_chip.dart';
import '../widgets/message_actions.dart';
import '../widgets/message_overview_content.dart';
import 'base.dart';
class MessageDetailsScreen extends ConsumerStatefulWidget {
const MessageDetailsScreen({
super.key,
required this.message,
this.blockExternalContent = false,
});
final Message message;
final bool blockExternalContent;
@override
ConsumerState<MessageDetailsScreen> createState() => _DetailsScreenState();
}
enum _OverflowMenuChoice { showContents, showSourceCode }
class _DetailsScreenState extends ConsumerState<MessageDetailsScreen> {
late PageController _pageController;
late MessageSource _source;
late Message _current;
@override
void initState() {
_pageController = PageController(initialPage: widget.message.sourceIndex);
_current = widget.message;
_source = _current.source;
super.initState();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
Future<Message> _getMessageAt(int index) {
if (_current.sourceIndex == index) {
return Future.value(_current);
}
return _source.getMessageAt(index);
}
bool _blockExternalContents(int index) =>
_current.sourceIndex == index && widget.blockExternalContent;
@override
Widget build(BuildContext context) {
final localizations = ref.text;
return ListenableBuilder(
listenable: _current,
builder: (context, child) => BasePage(
title: _current.mimeMessage.decodeSubject() ??
localizations.subjectUndefined,
appBarActions: [
//PlatformIconButton(icon: Icon(Icons.reply), onPressed: reply),
PlatformPopupMenuButton<_OverflowMenuChoice>(
onSelected: (_OverflowMenuChoice result) {
switch (result) {
case _OverflowMenuChoice.showContents:
context.pushNamed(Routes.mailContents, extra: _current);
break;
case _OverflowMenuChoice.showSourceCode:
_showSourceCode();
break;
}
},
itemBuilder: (BuildContext context) => [
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.showContents,
child: Text(localizations.viewContentsAction),
),
if (ref.read(settingsProvider).enableDeveloperMode)
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.showSourceCode,
child: Text(localizations.viewSourceAction),
),
],
),
],
bottom: MessageActions(message: _current),
content: PageView.builder(
controller: _pageController,
itemCount: _source.size,
itemBuilder: (context, index) => FutureBuilder<Message>(
future: _getMessageAt(index),
builder: (context, snapshot) {
final data = snapshot.data;
if (data == null) {
return const EmptyMessage();
}
return _MessageContent(
data,
blockExternalContents: _blockExternalContents(index),
);
},
),
onPageChanged: (index) async {
final current = await _getMessageAt(index);
setState(() {
_current = current;
});
},
),
),
);
}
void _showSourceCode() =>
context.pushNamed(Routes.sourceCode, extra: _current.mimeMessage);
}
class _MessageContent extends ConsumerStatefulWidget {
const _MessageContent(this.message, {this.blockExternalContents = false});
final Message message;
final bool blockExternalContents;
@override
ConsumerState<_MessageContent> createState() => _MessageContentState();
}
class _MessageContentState extends ConsumerState<_MessageContent> {
late bool _blockExternalImages;
bool _messageDownloadError = false;
bool _messageRequiresRefresh = false;
bool _isWebViewZoomedOut = false;
Object? errorObject;
StackTrace? errorStackTrace;
bool _notifyMarkedAsSeen = false;
late bool _settingsBlockExternalImages;
@override
void initState() {
final message = widget.message;
final mime = message.mimeMessage;
_settingsBlockExternalImages =
ref.read(settingsProvider).blockExternalImages;
if (widget.blockExternalContents) {
_blockExternalImages = true;
} else if (mime.isDownloaded) {
_blockExternalImages = _shouldImagesBeBlocked(mime);
if (!mime.isSeen) {
Future.delayed(const Duration(milliseconds: 50)).then(
(_) => message.source.markAsSeen(message, true),
);
}
} else {
_messageRequiresRefresh = mime.envelope == null;
_blockExternalImages = false;
}
_notifyMarkedAsSeen = !mime.isSeen;
super.initState();
}
@override
Widget build(BuildContext context) {
final localizations = ref.text;
return SingleChildScrollView(
child: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8),
child: _buildHeader(context, localizations),
),
_buildContent(localizations),
],
),
),
);
}
Widget _buildHeader(BuildContext context, AppLocalizations localizations) {
final mime = widget.message.mimeMessage;
final attachments = widget.message.attachments;
final date = ref.formatDateTime(mime.decodeDate());
final subject = mime.decodeSubject();
TableRow rowWithLabel({required String label, required Widget child}) =>
TableRow(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(0, 8, 8, 8),
child: Text(label),
),
child,
],
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Table(
defaultVerticalAlignment: TableCellVerticalAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
columnWidths: const {0: IntrinsicColumnWidth(), 1: FlexColumnWidth()},
children: [
rowWithLabel(
label: localizations.detailsHeaderFrom,
child: _buildMailAddresses(mime.from),
),
rowWithLabel(
label: localizations.detailsHeaderTo,
child: _buildMailAddresses(mime.to),
),
if (mime.cc?.isNotEmpty ?? false)
rowWithLabel(
label: localizations.detailsHeaderCc,
child: _buildMailAddresses(mime.cc),
),
rowWithLabel(
label: localizations.detailsHeaderDate,
child: Text(date),
),
],
),
SelectableText(
subject ?? localizations.subjectUndefined,
style: const TextStyle(fontWeight: FontWeight.bold),
),
_buildAttachments(attachments),
const Padding(
padding: EdgeInsets.all(8),
child: Divider(height: 2),
),
if (_blockExternalImages ||
mime.isNewsletter ||
mime.threadSequence != null ||
_isWebViewZoomedOut)
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
if (mime.threadSequence != null)
ThreadSequenceButton(message: widget.message)
else
const SizedBox.shrink(),
if (_isWebViewZoomedOut)
PlatformIconButton(
icon: const Icon(Icons.zoom_in),
onPressed: () => context.pushNamed(
Routes.mailContents,
extra: widget.message,
),
)
else
const SizedBox.shrink(),
if (_blockExternalImages)
PlatformElevatedButton(
child: Text(localizations.detailsActionShowImages),
onPressed: () => setState(
() {
_blockExternalImages = false;
},
),
)
else
const SizedBox.shrink(),
if (mime.isNewsletter)
UnsubscribeButton(
message: widget.message,
)
else
const SizedBox.shrink(),
],
),
if (ReadReceiptButton.shouldBeShown(mime, ref.read(settingsProvider)))
ReadReceiptButton(
message: widget.message,
),
],
);
}
Widget _buildMailAddresses(List<MailAddress>? addresses) {
if (addresses == null || addresses.isEmpty) {
return const SizedBox.shrink();
}
return MailAddressList(mailAddresses: addresses);
}
Widget _buildAttachments(List<ContentInfo> attachments) => Wrap(
children: [
for (final attachment in attachments)
AttachmentChip(info: attachment, message: widget.message),
],
);
Widget _buildMessageDownloadErrorContent(AppLocalizations localizations) =>
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8),
child: Text(localizations.detailsErrorDownloadInfo),
),
TextButton.icon(
icon: Icon(CommonPlatformIcons.refresh),
label: Text(localizations.detailsErrorDownloadRetry),
onPressed: () {
setState(() {
_messageDownloadError = false;
});
},
),
if (ref.read(settingsProvider).enableDeveloperMode) ...[
const Text('Details:'),
SelectableText(errorObject?.toString() ?? '<unknown error>'),
SelectableText(errorStackTrace?.toString() ?? '<no stacktrace>'),
TextButton.icon(
icon: const Icon(Icons.copy),
label: const Text('Copy to clipboard'),
onPressed: () {
final text =
'${errorObject?.toString() ?? '<unknown error>'} \n'
'${errorStackTrace?.toString() ?? '<no stacktrace>'}';
final data = ClipboardData(text: text);
Clipboard.setData(data);
},
),
],
],
);
Widget _buildContent(AppLocalizations localizations) {
if (_messageDownloadError) {
return _buildMessageDownloadErrorContent(localizations);
}
final message = widget.message;
return MimeMessageDownloader(
mimeMessage: message.mimeMessage,
fetchMessageContents: (
mimeMessage, {
int? maxSize,
bool markAsSeen = false,
List<MediaToptype>? includedInlineTypes,
Duration? responseTimeout,
}) =>
message.source.fetchMessageContents(
message,
maxSize: maxSize,
markAsSeen: markAsSeen,
includedInlineTypes: includedInlineTypes,
responseTimeout: responseTimeout,
),
markAsSeen: true,
onDownloaded: _onMimeMessageDownloaded,
onError: _onMimeMessageError,
blockExternalImages: _blockExternalImages,
preferPlainText: ref.read(settingsProvider).preferPlainTextMessages,
enableDarkMode: Theme.of(context).brightness == Brightness.dark,
mailtoDelegate: _handleMailto,
maxImageWidth: 320,
showMediaDelegate: _navigateToMedia,
includedInlineTypes: const [MediaToptype.image],
urlLauncherDelegate: (url) {
// skip canLaunch check due to bug when handling URLs registered by apps
// https://github.com/flutter/flutter/issues/93765
final uri = Uri.parse(
url.startsWith('http://')
? 'https://${url.substring('http://'.length)}'
: url,
);
launcher.launchUrl(
uri,
mode: ref.read(settingsProvider).urlLaunchMode,
);
return Future.value(true);
},
onZoomed: (controller, factor) {
if (factor < 0.9) {
setState(() {
_isWebViewZoomedOut = true;
});
}
},
logger: logger,
builder: (context, mimeMessage) {
final textCalendarPart =
mimeMessage.getAlternativePart(MediaSubtype.textCalendar);
if (textCalendarPart != null) {
// || mediaType.sub == MediaSubtype.applicationIcs)
final calendarText = textCalendarPart.decodeContentText();
if (calendarText != null) {
final mediaProvider =
TextMediaProvider('invite.ics', 'text/calendar', calendarText);
return IcalInteractiveMedia(
mediaProvider: mediaProvider,
message: widget.message,
);
}
}
return null;
},
);
}
bool _shouldImagesBeBlocked(MimeMessage mimeMessage) {
var blockExternalImages = widget.blockExternalContents ||
_settingsBlockExternalImages ||
widget.message.source.shouldBlockImages;
if (blockExternalImages) {
final html = mimeMessage.decodeTextHtmlPart();
final hasImages = (html != null) && (html.contains('<img '));
if (!hasImages) {
blockExternalImages = false;
}
}
return blockExternalImages;
}
// Update view after message has been downloaded successfully
void _onMimeMessageDownloaded(MimeMessage mimeMessage) {
widget.message.updateMime(mimeMessage);
final blockExternalImages = _shouldImagesBeBlocked(mimeMessage);
if (mounted &&
(_messageRequiresRefresh ||
mimeMessage.isSeen ||
mimeMessage.isNewsletter ||
mimeMessage.hasAttachments() ||
blockExternalImages)) {
setState(() {
_blockExternalImages = blockExternalImages;
});
}
NotificationService.instance.cancelNotificationForMessage(widget.message);
if (_notifyMarkedAsSeen) {
widget.message.source.onMarkedAsSeen(widget.message, true);
}
}
void _onMimeMessageError(Object? e, StackTrace? s) {
if (mounted) {
setState(() {
errorObject = e;
errorStackTrace = s;
_messageDownloadError = true;
});
}
}
Future _handleMailto(Uri mailto, MimeMessage mimeMessage) {
final messageBuilder = ref.read(
mailtoProvider(
mailtoUri: mailto,
originatingMessage: mimeMessage,
),
);
final composeData =
ComposeData([widget.message], messageBuilder, ComposeAction.newMessage);
return context.pushNamed(Routes.mailCompose, extra: composeData);
}
Future _navigateToMedia(InteractiveMediaWidget mediaWidget) =>
context.pushNamed(Routes.interactiveMedia, extra: mediaWidget);
// void _next() {
// _navigateToMessage(widget.message.next);
// }
// void _previous() {
// _navigateToMessage(widget.message.previous);
// }
// void _navigateToMessage(Message? message) {
// if (message != null) {
// locator<NavigationService>()
// .push(Routes.mailDetails, arguments: message, replace: true);
// }
// }
}
class MessageContentsScreen extends ConsumerWidget {
const MessageContentsScreen({super.key, required this.message});
final Message message;
@override
Widget build(BuildContext context, WidgetRef ref) => BasePage(
title: message.mimeMessage.decodeSubject() ?? ref.text.subjectUndefined,
content: SafeArea(
child: MimeMessageViewer(
mimeMessage: message.mimeMessage,
adjustHeight: false,
mailtoDelegate: (uri, mime) =>
_handleMailto(context, ref, uri, mime),
showMediaDelegate: (mediaViewer) =>
_navigateToMedia(context, mediaViewer),
enableDarkMode: Theme.of(context).brightness == Brightness.dark,
logger: logger,
),
),
);
Future _handleMailto(
BuildContext context,
WidgetRef ref,
Uri mailto,
MimeMessage mimeMessage,
) {
final messageBuilder = ref.read(
mailtoProvider(
mailtoUri: mailto,
originatingMessage: mimeMessage,
),
);
final composeData =
ComposeData([message], messageBuilder, ComposeAction.newMessage);
return context.pushNamed(Routes.mailCompose, extra: composeData);
}
Future _navigateToMedia(
BuildContext context,
InteractiveMediaWidget mediaWidget,
) =>
context.pushNamed(Routes.interactiveMedia, extra: mediaWidget);
}
class ThreadSequenceButton extends StatefulWidget {
const ThreadSequenceButton({super.key, required this.message});
final Message message;
@override
State<ThreadSequenceButton> createState() => _ThreadSequenceButtonState();
}
class _ThreadSequenceButtonState extends State<ThreadSequenceButton> {
OverlayEntry? _overlayEntry;
late Future<List<Message>> _loadingFuture;
@override
void dispose() {
if (_overlayEntry != null) {
_removeOverlay();
}
super.dispose();
}
@override
void initState() {
super.initState();
_loadingFuture = _loadMessages();
}
Future<List<Message>> _loadMessages() async {
final existingSource = widget.message.source;
if (existingSource is ListMessageSource) {
return existingSource.messages;
}
final threadSequence = widget.message.mimeMessage.threadSequence;
if (threadSequence == null || threadSequence.isEmpty) {
return [];
}
final mailClient =
widget.message.source.getMimeSource(widget.message)?.mailClient;
if (mailClient == null) {
return [];
}
final mimeMessages = await mailClient.fetchMessageSequence(
threadSequence,
fetchPreference: FetchPreference.envelope,
);
final source = ListMessageSource(widget.message.source)
..initWithMimeMessages(mimeMessages);
return source.messages;
}
@override
Widget build(BuildContext context) {
final length = widget.message.mimeMessage.threadSequence?.length ?? 0;
return WillPopScope(
onWillPop: () {
if (_overlayEntry == null) {
return Future.value(true);
}
_removeOverlay();
return Future.value(false);
},
child: PlatformIconButton(
icon: IconService.buildNumericIcon(context, length),
onPressed: () {
if (_overlayEntry != null) {
_removeOverlay();
} else {
final overlayEntry = _buildThreadsOverlay();
_overlayEntry = overlayEntry;
Overlay.of(context).insert(overlayEntry);
}
},
),
);
}
void _removeOverlay() {
final overlayEntry = _overlayEntry;
if (overlayEntry != null) {
overlayEntry.remove();
_overlayEntry = null;
}
}
void _select(Message message) {
_removeOverlay();
context.pushNamed(Routes.mailDetails, extra: message);
}
OverlayEntry _buildThreadsOverlay() {
final renderBox = context.findRenderObject() as RenderBox?;
final offset = renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
final renderSize = renderBox?.size ?? const Size(120, 400);
final size = MediaQuery.of(context).size;
final currentUid = widget.message.mimeMessage.uid;
final top = offset.dy + renderSize.height + 5.0;
final height = size.height - top - 16;
return OverlayEntry(
builder: (context) => GestureDetector(
onTap: _removeOverlay,
child: Stack(
children: [
Positioned.fill(child: Container(color: const Color(0x09000000))),
Positioned(
left: offset.dx,
top: top,
width: size.width - offset.dx - 16,
child: Material(
elevation: 4,
child: FutureBuilder<List<Message>?>(
future: _loadingFuture,
builder: (context, snapshot) {
final data = snapshot.data;
if (data == null) {
return const Center(
child: PlatformProgressIndicator(),
);
}
final messages = data;
final isSentFolder = widget.message.source.isSent;
return ConstrainedBox(
constraints: BoxConstraints(maxHeight: height),
child: ListView(
padding: EdgeInsets.zero,
shrinkWrap: true,
children: messages
.map((message) => SelectablePlatformListTile(
title: MessageOverviewContent(
message: message,
isSentMessage: isSentFolder,
),
onTap: () => _select(message),
selected:
message.mimeMessage.uid == currentUid,
))
.toList(),
),
);
},
),
),
),
],
),
),
);
}
}
class ReadReceiptButton extends StatefulHookConsumerWidget {
const ReadReceiptButton({super.key, required this.message});
final Message message;
@override
ConsumerState<ReadReceiptButton> createState() => _ReadReceiptButtonState();
static bool shouldBeShown(MimeMessage mime, Settings settings) =>
(mime.isReadReceiptSent || mime.isReadReceiptRequested) &&
(settings.readReceiptDisplaySetting != ReadReceiptDisplaySetting.never);
}
class _ReadReceiptButtonState extends ConsumerState<ReadReceiptButton> {
bool _isSendingReadReceipt = false;
@override
Widget build(BuildContext context) {
final message = widget.message;
final mime = message.mimeMessage;
final localizations = ref.text;
if (mime.isReadReceiptSent) {
return Text(
localizations.detailsReadReceiptSentStatus,
style: Theme.of(context).textTheme.bodySmall,
);
} else if (_isSendingReadReceipt) {
return const PlatformProgressIndicator();
} else {
return ElevatedButton(
child: Text(localizations.detailsSendReadReceiptAction),
onPressed: () async {
setState(() {
_isSendingReadReceipt = true;
});
final mailClient = message.source.getMimeSource(message)?.mailClient;
if (mailClient == null) {
return;
}
final readReceipt = MessageBuilder.buildReadReceipt(
mime,
message.account.fromAddress,
reportingUa: 'Maily 1.0',
subject: localizations.detailsReadReceiptSubject,
);
await mailClient.sendMessage(readReceipt, appendToSent: false);
await mailClient.flagMessage(mime, isReadReceiptSent: true);
setState(() {
_isSendingReadReceipt = false;
});
},
);
}
}
}
class UnsubscribeButton extends StatefulHookConsumerWidget {
const UnsubscribeButton({super.key, required this.message});
final Message message;
@override
ConsumerState<UnsubscribeButton> createState() => _UnsubscribeButtonState();
}
class _UnsubscribeButtonState extends ConsumerState<UnsubscribeButton> {
bool _isActive = false;
@override
Widget build(BuildContext context) {
if (_isActive) {
return const PlatformProgressIndicator();
}
final localizations = ref.text;
return widget.message.isNewsletterUnsubscribed
? widget.message.isNewsLetterSubscribable
? PlatformElevatedButton(
onPressed: _resubscribe,
child: Text(localizations.detailsNewsletterActionResubscribe),
)
: Text(
localizations.detailsNewsletterStatusUnsubscribed,
style: const TextStyle(fontStyle: FontStyle.italic),
)
: PlatformElevatedButton(
onPressed: _unsubscribe,
child: Text(localizations.detailsNewsletterActionUnsubscribe),
);
}
Future<void> _resubscribe() async {
final localizations = ref.text;
final mime = widget.message.mimeMessage;
final listName = mime.decodeListName() ?? '<>';
final confirmation = await LocalizedDialogHelper.askForConfirmation(
ref,
title: localizations.detailsNewsletterResubscribeDialogTitle,
action: localizations.detailsNewsletterResubscribeDialogAction,
query: localizations.detailsNewsletterResubscribeDialogQuestion(listName),
);
if (confirmation ?? false) {
setState(() {
_isActive = true;
});
final mailClient =
widget.message.source.getMimeSource(widget.message)?.mailClient;
final subscribed = mailClient != null && await mime.subscribe(mailClient);
setState(() {
_isActive = false;
});
if (subscribed) {
setState(() {
widget.message.isNewsletterUnsubscribed = false;
});
// TODO(RV): store flag only when server/mailbox supports arbitrary flags?
await mailClient.store(
MessageSequence.fromMessage(mime),
[Message.keywordFlagUnsubscribed],
action: StoreAction.remove,
);
}
if (context.mounted) {
await LocalizedDialogHelper.showTextDialog(
ref,
subscribed
? localizations.detailsNewsletterResubscribeSuccessTitle
: localizations.detailsNewsletterResubscribeFailureTitle,
subscribed
? localizations
.detailsNewsletterResubscribeSuccessMessage(listName)
: localizations
.detailsNewsletterResubscribeFailureMessage(listName),
);
}
}
}
Future<void> _unsubscribe() async {
final localizations = ref.text;
final mime = widget.message.mimeMessage;
final listName = mime.decodeListName() ?? '<>';
final confirmation = await LocalizedDialogHelper.askForConfirmation(
ref,
title: localizations.detailsNewsletterUnsubscribeDialogTitle,
action: localizations.detailsNewsletterUnsubscribeDialogAction,
query: localizations.detailsNewsletterUnsubscribeDialogQuestion(listName),
);
if (confirmation ?? false) {
setState(() {
_isActive = true;
});
final mailClient =
widget.message.source.getMimeSource(widget.message)?.mailClient;
var unsubscribed = false;
try {
unsubscribed = mailClient != null && await mime.unsubscribe(mailClient);
} catch (e, s) {
if (kDebugMode) {
print('error during unsubscribe: $e $s');
}
}
setState(() {
_isActive = false;
});
if (unsubscribed) {
setState(() {
widget.message.isNewsletterUnsubscribed = true;
});
// TODO(RV): store flag only when server/mailbox supports arbitrary flags?
try {
await mailClient?.store(
MessageSequence.fromMessage(mime),
[Message.keywordFlagUnsubscribed],
);
} catch (e, s) {
if (kDebugMode) {
print('error during unsubscribe flag store operation: $e $s');
}
}
}
if (context.mounted) {
await LocalizedDialogHelper.showTextDialog(
ref,
unsubscribed
? localizations.detailsNewsletterUnsubscribeSuccessTitle
: localizations.detailsNewsletterUnsubscribeFailureTitle,
unsubscribed
? localizations
.detailsNewsletterUnsubscribeSuccessMessage(listName)
: localizations
.detailsNewsletterUnsubscribeFailureMessage(listName),
);
}
}
}
}
class MailAddressList extends StatefulWidget {
const MailAddressList({super.key, required this.mailAddresses});
final List<MailAddress> mailAddresses;
@override
State<MailAddressList> createState() => _MailAddressListState();
}
class _MailAddressListState extends State<MailAddressList> {
bool _isExpanded = false;
@override
Widget build(BuildContext context) => ExpansionWrap(
spacing: 4,
expandIndicator: DensePlatformIconButton(
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: () {
setState(() {
_isExpanded = true;
});
},
),
compressIndicator: DensePlatformIconButton(
icon: const Icon(Icons.keyboard_arrow_up),
onPressed: () {
setState(() {
_isExpanded = false;
});
},
),
isExpanded: _isExpanded,
maxRuns: 2,
children: [
for (final address in widget.mailAddresses)
MailAddressChip(mailAddress: address),
],
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/account_server_details_screen.dart
|
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/model.dart';
import '../account/provider.dart';
import '../localization/extension.dart';
import '../mail/provider.dart';
import '../util/localized_dialog_helper.dart';
import '../widgets/password_field.dart';
import 'base.dart';
import 'mail_screen_for_default_account.dart';
/// Allows to edit server details for an account.
class AccountServerDetailsScreen extends ConsumerWidget {
/// Creates a [AccountServerDetailsScreen].
const AccountServerDetailsScreen({
super.key,
this.accountEmail,
this.account,
this.title,
});
/// The email address of the account to edit.
final String? accountEmail;
/// The account to edit.
final RealAccount? account;
/// The title of the screen, if it should differ from the account's name.
final String? title;
@override
Widget build(BuildContext context, WidgetRef ref) {
final accountEmail = this.accountEmail;
final account = this.account ??
(accountEmail != null
? ref.watch(
findRealAccountByEmailProvider(email: accountEmail),
)
: null);
if (account == null) {
return const MailScreenForDefaultAccount();
}
final editor = AccountServerDetailsEditor(account: account);
return BasePage(
title: title ?? account.name,
content: editor,
appBarActions: const [
_SaveButton(),
],
);
}
}
class AccountServerDetailsEditor extends StatefulHookConsumerWidget {
const AccountServerDetailsEditor({
super.key,
required this.account,
});
final RealAccount account;
@override
ConsumerState<AccountServerDetailsEditor> createState() =>
_AccountServerDetailsEditorState();
Future<void> testConnection(BuildContext context) async {
await _AccountServerDetailsEditorState._currentState
?.testConnection(context);
}
}
class _SaveButton extends StatefulWidget {
const _SaveButton();
@override
_SaveButtonState createState() => _SaveButtonState();
}
class _SaveButtonState extends State<_SaveButton> {
var _isSaving = false;
@override
Widget build(BuildContext context) {
if (_isSaving) {
return const PlatformProgressIndicator();
}
return PlatformIconButton(
icon: Icon(PlatformInfo.isCupertino
? CupertinoIcons.check_mark_circled
: Icons.save),
onPressed: () async {
setState(() {
_isSaving = true;
});
await _AccountServerDetailsEditorState._currentState
?.testConnection(context);
if (mounted) {
setState(() {
_isSaving = false;
});
}
},
);
}
}
class _AccountServerDetailsEditorState
extends ConsumerState<AccountServerDetailsEditor> {
static _AccountServerDetailsEditorState? _currentState;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _userNameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _incomingHostDomainController =
TextEditingController();
final TextEditingController _incomingHostPortController =
TextEditingController();
final TextEditingController _incomingUserNameController =
TextEditingController();
final TextEditingController _incomingPasswordController =
TextEditingController();
late SocketType _incomingSecurity;
late ServerType _incomingServerType;
final TextEditingController _outgoingHostDomainController =
TextEditingController();
final TextEditingController _outgoingHostPortController =
TextEditingController();
final TextEditingController _outgoingUserNameController =
TextEditingController();
final TextEditingController _outgoingPasswordController =
TextEditingController();
late SocketType _outgoingSecurity;
late ServerType _outgoingServerType;
@override
void initState() {
_currentState = this;
final mailAccount = widget.account.mailAccount;
final incoming = mailAccount.incoming;
final incomingAuth =
incoming.authentication as UserNameBasedAuthentication?;
final outgoing = mailAccount.outgoing;
final outgoingAuth =
outgoing.authentication as UserNameBasedAuthentication?;
_emailController.text = mailAccount.email;
_setupFields(
incoming.serverConfig,
outgoing.serverConfig,
incomingAuth,
outgoingAuth,
);
super.initState();
}
void _setupFields(
ServerConfig? incoming,
ServerConfig? outgoing,
UserNameBasedAuthentication? incomingAuth,
UserNameBasedAuthentication? outgoingAuth,
) {
final incomingPassword =
incomingAuth is PlainAuthentication ? incomingAuth.password : null;
if (incomingAuth?.userName != null) {
_userNameController.text = incomingAuth?.userName ?? '';
}
if (incomingPassword != null) {
_passwordController.text = incomingPassword;
}
final incomingHostName = incoming?.hostname;
_incomingHostDomainController.text = incomingHostName ?? '';
_incomingHostPortController.text = incoming?.port.toString() ?? '';
if (incomingAuth?.userName != null) {
_incomingUserNameController.text = incomingAuth?.userName ?? '';
}
if (incomingPassword != null) {
_incomingPasswordController.text = incomingPassword;
}
_incomingSecurity = incoming?.socketType ?? SocketType.ssl;
_incomingServerType = incoming?.type ?? ServerType.imap;
_outgoingHostDomainController.text = outgoing?.hostname ?? '';
_outgoingHostPortController.text = outgoing?.port.toString() ?? '';
if (outgoingAuth?.userName != null) {
_outgoingUserNameController.text = outgoingAuth?.userName ?? '';
}
if (outgoingAuth is PlainAuthentication) {
_outgoingPasswordController.text = outgoingAuth.password;
}
_outgoingSecurity = outgoing?.socketType ?? SocketType.ssl;
_outgoingServerType = outgoing?.type ?? ServerType.smtp;
}
@override
void dispose() {
_emailController.dispose();
_userNameController.dispose();
_passwordController.dispose();
_incomingHostDomainController.dispose();
_incomingHostPortController.dispose();
_incomingUserNameController.dispose();
_incomingPasswordController.dispose();
_outgoingHostDomainController.dispose();
_outgoingHostPortController.dispose();
_outgoingUserNameController.dispose();
_outgoingPasswordController.dispose();
super.dispose();
}
Future<void> testConnection(BuildContext context) async {
final localizations = ref.text;
final mailAccount = widget.account.mailAccount;
final userName = (_userNameController.text.isEmpty)
? mailAccount.email
: _userNameController.text;
final password = _passwordController.text;
final incomingServerConfig = ServerConfig(
type: _incomingServerType,
hostname: _incomingHostDomainController.text,
port: int.tryParse(_incomingHostPortController.text) ?? 0,
socketType: _incomingSecurity,
authentication: Authentication.plain,
usernameType: UsernameType.unknown,
);
final incomingUserName = (_incomingUserNameController.text.isEmpty)
? userName
: _incomingUserNameController.text;
final incomingPassword = (_incomingPasswordController.text.isEmpty)
? password
: _incomingPasswordController.text;
final outgoingServerConfig = ServerConfig(
type: _outgoingServerType,
hostname: _outgoingHostDomainController.text,
port: int.tryParse(_outgoingHostPortController.text) ?? 0,
socketType: _outgoingSecurity,
authentication: Authentication.plain,
usernameType: UsernameType.unknown,
);
final outgoingUserName = (_outgoingUserNameController.text.isEmpty)
? userName
: _outgoingUserNameController.text;
final outgoingPassword = (_outgoingPasswordController.text.isEmpty)
? password
: _outgoingPasswordController.text;
final newAccount = mailAccount.copyWith(
email: _emailController.text,
userName: userName,
incoming: MailServerConfig(
serverConfig: incomingServerConfig,
authentication: PlainAuthentication(incomingUserName, incomingPassword),
),
outgoing: MailServerConfig(
serverConfig: outgoingServerConfig,
authentication: PlainAuthentication(outgoingUserName, outgoingPassword),
),
);
//print('account: $mailAccount');
final completedAccount = await Discover.complete(newAccount);
if (completedAccount == null) {
if (mounted) {
await LocalizedDialogHelper.showTextDialog(
ref,
localizations.errorTitle,
localizations.accountDetailsErrorHostProblem(
_incomingHostDomainController.text,
_outgoingHostDomainController.text,
),
);
}
return;
} else {
final incoming = mailAccount.incoming;
final outgoing = mailAccount.outgoing;
if (mounted) {
setState(() {
_incomingHostPortController.text =
incoming.serverConfig.port.toString();
_incomingServerType = incoming.serverConfig.type;
_incomingSecurity = incoming.serverConfig.socketType;
_outgoingHostPortController.text =
outgoing.serverConfig.port.toString();
_outgoingServerType = outgoing.serverConfig.type;
_outgoingSecurity = outgoing.serverConfig.socketType;
});
}
}
// now try to sign in:
final connectedAccount = await ref.read(
firstTimeMailClientSourceProvider(
account: RealAccount(mailAccount),
).future,
);
final mailClient = connectedAccount?.mailClient;
if (mailClient != null && mailClient.isConnected) {
if (context.mounted) {
context.pop(connectedAccount);
}
} else if (mounted) {
await LocalizedDialogHelper.showTextDialog(
ref,
localizations.errorTitle,
localizations.accountDetailsErrorLoginProblem(
incomingUserName,
password,
),
);
}
}
@override
Widget build(BuildContext context) {
final localizations = ref.text;
return SingleChildScrollView(
child: Material(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: [
DecoratedPlatformTextField(
autocorrect: false,
controller: _emailController,
decoration: InputDecoration(
labelText: localizations.addAccountEmailLabel,
hintText: localizations.addAccountEmailHint,
),
),
DecoratedPlatformTextField(
autocorrect: false,
controller: _userNameController,
decoration: InputDecoration(
labelText: localizations.accountDetailsUserNameLabel,
hintText: localizations.accountDetailsUserNameHint,
),
),
PasswordField(
controller: _passwordController,
labelText: localizations.accountDetailsPasswordLabel,
hintText: localizations.accountDetailsPasswordHint,
),
ExpansionTile(
title: Text(localizations.accountDetailsBaseSectionTitle),
initiallyExpanded: true,
children: [
DecoratedPlatformTextField(
autocorrect: false,
controller: _incomingHostDomainController,
decoration: InputDecoration(
labelText: localizations.accountDetailsIncomingLabel,
hintText: localizations.accountDetailsIncomingHint,
),
),
DecoratedPlatformTextField(
autocorrect: false,
controller: _outgoingHostDomainController,
decoration: InputDecoration(
labelText: localizations.accountDetailsOutgoingLabel,
hintText: localizations.accountDetailsOutgoingHint,
),
),
],
),
ExpansionTile(
title: Text(
localizations.accountDetailsAdvancedIncomingSectionTitle,
),
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(localizations
.accountDetailsIncomingServerTypeLabel),
),
PlatformDropdownButton<ServerType>(
items: [
DropdownMenuItem(
child: Text(
localizations.accountDetailsOptionAutomatic,
),
),
const DropdownMenuItem(
value: ServerType.imap,
child: Text('IMAP'),
),
const DropdownMenuItem(
value: ServerType.pop,
child: Text('POP'),
),
],
value: _incomingServerType,
onChanged: (value) {
if (value != null) {
setState(
() => _incomingServerType = value,
);
}
},
),
],
),
Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(localizations
.accountDetailsIncomingSecurityLabel),
),
PlatformDropdownButton<SocketType>(
items: [
DropdownMenuItem(
child: Text(
localizations.accountDetailsOptionAutomatic,
),
),
const DropdownMenuItem(
value: SocketType.ssl,
child: Text('SSL'),
),
const DropdownMenuItem(
// cSpell: ignore starttls
value: SocketType.starttls,
child: Text('Start TLS'),
),
DropdownMenuItem(
value: SocketType.plain,
child: Text(localizations
.accountDetailsSecurityOptionNone),
),
],
value: _incomingSecurity,
onChanged: (value) {
if (value != null) {
setState(() => _incomingSecurity = value);
}
},
),
],
),
DecoratedPlatformTextField(
autocorrect: false,
controller: _incomingHostPortController,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration: InputDecoration(
labelText:
localizations.accountDetailsIncomingPortLabel,
hintText: localizations.accountDetailsPortHint,
),
),
DecoratedPlatformTextField(
autocorrect: false,
controller: _incomingUserNameController,
decoration: InputDecoration(
labelText:
localizations.accountDetailsIncomingUserNameLabel,
hintText:
localizations.accountDetailsAlternativeUserNameHint,
),
),
PasswordField(
controller: _incomingPasswordController,
labelText:
localizations.accountDetailsIncomingPasswordLabel,
hintText:
localizations.accountDetailsAlternativePasswordHint,
),
],
),
ExpansionTile(
title: Text(
localizations.accountDetailsAdvancedOutgoingSectionTitle,
),
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(
localizations.accountDetailsOutgoingServerTypeLabel,
),
),
PlatformDropdownButton<ServerType>(
items: [
DropdownMenuItem(
child: Text(
localizations.accountDetailsOptionAutomatic,
),
),
const DropdownMenuItem(
value: ServerType.smtp,
child: Text('SMTP'),
),
],
value: _outgoingServerType,
onChanged: (value) {
if (value != null) {
setState(() => _outgoingServerType = value);
}
},
),
],
),
Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(localizations
.accountDetailsOutgoingSecurityLabel),
),
PlatformDropdownButton<SocketType>(
items: [
DropdownMenuItem(
child: Text(
localizations.accountDetailsOptionAutomatic,
),
),
const DropdownMenuItem(
value: SocketType.ssl,
child: Text('SSL'),
),
const DropdownMenuItem(
value: SocketType.starttls,
child: Text('Start TLS'),
),
DropdownMenuItem(
value: SocketType.plain,
child: Text(
localizations.accountDetailsSecurityOptionNone,
),
),
],
value: _outgoingSecurity,
onChanged: (value) {
if (value != null) {
setState(() => _outgoingSecurity = value);
}
},
),
],
),
DecoratedPlatformTextField(
autocorrect: false,
controller: _outgoingHostPortController,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration: InputDecoration(
labelText:
localizations.accountDetailsOutgoingPortLabel,
hintText: localizations.accountDetailsPortHint,
),
),
DecoratedPlatformTextField(
autocorrect: false,
controller: _outgoingUserNameController,
decoration: InputDecoration(
labelText:
localizations.accountDetailsOutgoingUserNameLabel,
hintText:
localizations.accountDetailsAlternativeUserNameHint,
),
),
PasswordField(
controller: _outgoingPasswordController,
labelText:
localizations.accountDetailsOutgoingPasswordLabel,
hintText:
localizations.accountDetailsAlternativePasswordHint,
),
],
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/mail_search_screen.dart
|
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_platform_widgets/platform.dart';
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../localization/extension.dart';
import '../mail/provider.dart';
import 'base.dart';
import 'message_source_screen.dart';
/// Displays the search result for
class MailSearchScreen extends ConsumerWidget {
/// Creates a [MailSearchScreen]
const MailSearchScreen({
super.key,
required this.search,
});
/// The account to display
final MailSearch search;
@override
Widget build(BuildContext context, WidgetRef ref) {
final text = ref.text;
final searchSource = ref.watch(
mailSearchProvider(
localizations: text,
search: search,
),
);
return searchSource.when(
loading: () => BasePage(
title: text.searchQueryTitle(search.query),
content: const Center(
child: PlatformProgressIndicator(),
),
),
error: (error, stack) => BasePage(
title: text.searchQueryTitle(search.query),
content: Center(child: Text('$error')),
),
data: (source) => MessageSourceScreen(messageSource: source),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/base.dart
|
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/provider.dart';
import '../widgets/app_drawer.dart';
import '../widgets/menu_with_badge.dart';
/// Provides a basic page layout with an app bar and a drawer.
class BasePage extends ConsumerWidget {
/// Creates a new [BasePage].
const BasePage({
super.key,
this.title,
this.subtitle,
this.content,
this.floatingActionButton,
this.appBarActions,
this.appBar,
this.drawer,
this.bottom,
this.includeDrawer = true,
});
/// The title of the page.
final String? title;
/// The subtitle of the page.
final String? subtitle;
/// The content of the page.
final Widget? content;
/// The floating action button of the page.
final FloatingActionButton? floatingActionButton;
/// The actions of the app bar.
final List<Widget>? appBarActions;
/// The app bar.
final PlatformAppBar? appBar;
/// The drawer.
final Widget? drawer;
/// The bottom widget.
final Widget? bottom;
/// Whether to include the drawer.
final bool includeDrawer;
@override
Widget build(BuildContext context, WidgetRef ref) {
PlatformAppBar? buildAppBar() {
final title = this.title;
if (title == null && subtitle == null && appBarActions == null) {
return null;
}
final floatingActionButton = this.floatingActionButton;
return PlatformAppBar(
material: (context, platform) => MaterialAppBarData(
elevation: 0,
),
cupertino: (context, platform) => CupertinoNavigationBarData(
transitionBetweenRoutes: false,
trailing: floatingActionButton == null
? null
: CupertinoButton(
onPressed: floatingActionButton.onPressed,
child: floatingActionButton.child ?? const SizedBox.shrink(),
),
),
leading: (includeDrawer && ref.watch(hasAccountWithErrorProvider))
? const MenuWithBadge()
: null,
title: (title == null && subtitle == null)
? null
: BaseTitle(
title: title ?? '',
subtitle: subtitle,
),
automaticallyImplyLeading: true,
trailingActions: appBarActions ?? [],
);
}
return PlatformPageScaffold(
appBar: buildAppBar(),
body: content,
bottomBar: bottom,
material: (context, platform) => MaterialScaffoldData(
drawer: drawer ?? (includeDrawer ? const AppDrawer() : null),
floatingActionButton: floatingActionButton,
// bottomNavBar: bottom,
),
);
}
}
/// Renders a title consisting of a title and an optional subtitle.
class BaseTitle extends StatelessWidget {
/// Creates a new [BaseTitle].
const BaseTitle({
super.key,
required this.title,
this.subtitle,
});
/// The title of the app bar.
final String title;
/// The subtitle of the app bar.
final String? subtitle;
@override
Widget build(BuildContext context) {
final subtitle = this.subtitle;
return subtitle == null
? Text(title, overflow: TextOverflow.fade)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, overflow: TextOverflow.fade),
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
subtitle,
overflow: TextOverflow.fade,
style: const TextStyle(
fontSize: 10,
fontStyle: FontStyle.italic,
),
),
),
],
);
}
}
class SliverSingleChildHeaderDelegate extends SliverPersistentHeaderDelegate {
SliverSingleChildHeaderDelegate({
required this.maxHeight,
required this.minHeight,
required this.child,
this.elevation,
this.background,
});
final double maxHeight;
final double minHeight;
final double? elevation;
final Widget child;
final Widget? background;
@override
Widget build(
BuildContext context,
double shrinkOffset,
bool overlapsContent,
) =>
Material(
elevation: elevation ?? 0,
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: maxHeight),
child: Stack(
children: [
Positioned(
bottom: 0,
left: 0,
right: 0,
top: 0,
child: background ?? const SizedBox.shrink(),
),
child,
],
),
),
);
@override
double get maxExtent => kToolbarHeight + maxHeight;
@override
double get minExtent => kToolbarHeight + minHeight;
@override
bool shouldRebuild(SliverSingleChildHeaderDelegate oldDelegate) =>
maxHeight != oldDelegate.maxHeight ||
minHeight != oldDelegate.minHeight ||
child != oldDelegate.child;
}
class CustomApBarSliverDelegate extends SliverPersistentHeaderDelegate {
CustomApBarSliverDelegate({
this.title,
this.child,
this.maxHeight = 350,
this.background,
this.minHeight = 0,
});
final Widget? child;
final Widget? title;
final Widget? background;
final double minHeight;
final double maxHeight;
@override
Widget build(
BuildContext context,
double shrinkOffset,
bool overlapsContent,
) {
final appBarSize = maxExtent - shrinkOffset;
final proportion = 2 - (maxExtent / appBarSize);
final percent = proportion < 0 || proportion > 1 ? 0.0 : proportion;
return ConstrainedBox(
constraints: BoxConstraints(minHeight: maxHeight),
child: Stack(
children: [
Positioned(
bottom: 0,
left: 0,
right: 0,
top: 0,
child: background ?? const SizedBox.shrink(),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Opacity(opacity: percent, child: child),
),
Positioned(
top: 0,
left: 0,
right: 0,
child: AppBar(
title: Opacity(opacity: 1 - percent, child: title),
backgroundColor: Colors.transparent,
elevation: 0,
),
),
],
),
);
}
@override
OverScrollHeaderStretchConfiguration get stretchConfiguration =>
OverScrollHeaderStretchConfiguration();
@override
double get minExtent => kToolbarHeight + minHeight;
@override
double get maxExtent => kToolbarHeight + maxHeight;
@override
bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) => true;
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/email_screen.dart
|
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/provider.dart';
import '../mail/provider.dart';
import 'base.dart';
import 'error_screen.dart';
import 'screens.dart';
/// Displays the mail for a given account
class EMailScreen extends ConsumerWidget {
/// Creates a [EMailScreen]
const EMailScreen({super.key, required this.email, this.encodedMailboxPath});
/// The email of the account to display
final String email;
/// The optional mailbox encoded path
final String? encodedMailboxPath;
@override
Widget build(BuildContext context, WidgetRef ref) {
final account = ref.watch(findAccountByEmailProvider(email: email));
final encodedMailboxPath = this.encodedMailboxPath;
if (account == null) {
if (ref.read(realAccountsProvider).isEmpty) {
return const WelcomeScreen();
}
return const MailScreenForDefaultAccount();
}
if (encodedMailboxPath == null) {
return MailScreen(
account: account,
);
}
final mailboxValue = ref.watch(
findMailboxProvider(
account: account,
encodedMailboxPath: encodedMailboxPath,
),
);
return mailboxValue.when(
loading: () => const BasePage(
content: Center(
child: PlatformProgressIndicator(),
),
),
error: (error, stack) => ErrorScreen(error: error, stackTrace: stack),
data: (mailbox) => MailScreen(
account: account,
mailbox: mailbox,
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/compose_screen.dart
|
import 'dart:async';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:enough_html_editor/enough_html_editor.dart';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_mail_html/enough_mail_html.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:enough_text_editor/enough_text_editor.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/model.dart';
import '../account/provider.dart';
import '../contact/provider.dart';
import '../localization/app_localizations.g.dart';
import '../localization/extension.dart';
import '../mail/provider.dart';
import '../models/compose_data.dart';
import '../models/message.dart';
import '../models/sender.dart';
import '../routes/routes.dart';
import '../scaffold_messenger/service.dart';
import '../settings/provider.dart';
import '../share/model.dart';
import '../share/provider.dart';
import '../util/localized_dialog_helper.dart';
import '../widgets/app_drawer.dart';
import '../widgets/attachment_compose_bar.dart';
import '../widgets/editor_extensions.dart';
import '../widgets/recipient_input_field.dart';
enum _OverflowMenuChoice {
showSourceCode,
saveAsDraft,
requestReadReceipt,
convertToPlainTextEditor,
convertToHtmlEditor
}
enum _Autofocus { to, subject, text }
/// A dropdown to select the sender
class SenderDropdown extends HookConsumerWidget {
/// Creates a new [SenderDropdown] with the given [onChanged]
const SenderDropdown({
super.key,
required this.onChanged,
this.from,
});
/// Callback when the selected sender changes
final ValueChanged<Sender> onChanged;
/// Optional list of from sender addresses
final List<MailAddress>? from;
@override
Widget build(BuildContext context, WidgetRef ref) {
// TODO(RV): consider adding first from as sender
final senders = ref.watch(sendersProvider);
Sender getInitialSender() {
final from = this.from;
if (from != null && from.isNotEmpty) {
final senderEmail = from.first.email.toLowerCase();
final sender = senders.firstWhereOrNull(
(s) => s.address.email.toLowerCase() == senderEmail,
);
if (sender != null) {
return sender;
}
}
final defaultSender = ref.read(settingsProvider).defaultSender;
if (defaultSender != null) {
final senderEmail = defaultSender.email.toLowerCase();
final sender = senders.firstWhereOrNull(
(s) => s.address.email.toLowerCase() == senderEmail,
);
if (sender != null) {
return sender;
}
}
final account = ref.read(currentRealAccountProvider);
if (account != null) {
final senderEmail = account.fromAddress.email.toLowerCase();
final sender = senders.firstWhereOrNull(
(s) => s.address.email.toLowerCase() == senderEmail,
);
if (sender != null) {
return sender;
}
}
return senders.first;
}
final senderState = useState(getInitialSender());
return PlatformDropdownButton<Sender>(
material: (context, platform) => MaterialDropdownButtonData(
isExpanded: true,
),
items: senders
.map(
(s) => DropdownMenuItem<Sender>(
value: s,
child: Text(
s.toString(),
overflow: TextOverflow.fade,
),
),
)
.toList(),
onChanged: (s) async {
if (s != null) {
senderState.value = s;
onChanged(s);
}
},
value: senderState.value,
hint: Text(ref.text.composeSenderHint),
);
}
}
/// Compose a new email message
class ComposeScreen extends ConsumerStatefulWidget {
/// Creates a new [ComposeScreen] with the given [ComposeData
const ComposeScreen({super.key, required this.data});
/// The initial data for composing the message
final ComposeData data;
@override
ConsumerState<ComposeScreen> createState() => _ComposeScreenState();
}
class _ComposeScreenState extends ConsumerState<ComposeScreen> {
late List<MailAddress> _toRecipients;
late List<MailAddress> _ccRecipients;
late List<MailAddress> _bccRecipients;
final TextEditingController _subjectController = TextEditingController();
final TextEditingController _plainTextController = TextEditingController();
late Sender _from;
late List<Sender> _senders;
_Autofocus? _focus;
bool _isCcBccVisible = false;
Future<String>? _loadMailTextFuture;
HtmlEditorApi? _htmlEditorApi;
Future? _downloadAttachmentsFuture;
ComposeData? _resumeComposeData;
bool _isReadReceiptRequested = false;
late ComposeMode _composeMode;
late RealAccount _realAccount;
TextEditorApi? _plainTextEditorApi;
@override
void didChangeDependencies() {
onSharedData = _onSharedData;
_composeMode = widget.data.composeMode;
final mb = widget.data.messageBuilder;
_toRecipients = mb.to ?? [];
_ccRecipients = mb.cc ?? [];
_bccRecipients = mb.bcc ?? [];
_isCcBccVisible = _ccRecipients.isNotEmpty || _bccRecipients.isNotEmpty;
_subjectController.text = mb.subject ?? '';
_focus = (_toRecipients.isEmpty && _ccRecipients.isEmpty)
? _Autofocus.to
: (_subjectController.text.isEmpty)
? _Autofocus.subject
: _Autofocus.text;
_senders = ref.read(sendersProvider);
final currentAccount = ref.read(currentRealAccountProvider)!;
_realAccount = currentAccount;
final defaultSender = ref.read(settingsProvider).defaultSender;
final mbFrom = mb.from ?? [defaultSender ?? currentAccount.fromAddress];
mb.from ??= mbFrom;
Sender? from;
if (mbFrom.first == defaultSender) {
from = _senders
.firstWhereOrNull((sender) => sender.address == defaultSender);
} else {
final senderEmail = mb.from?.first.email.toLowerCase();
from = _senders.firstWhereOrNull(
(s) => s.address.email.toLowerCase() == senderEmail,
);
}
if (from == null) {
from = Sender(mbFrom.first, currentAccount);
_senders = [from, ..._senders];
}
_from = from;
_checkAccountContactManager(_from.account);
_loadMailTextFuture = widget.data.resumeText != null
? _loadMailTextFromComposeData()
: _loadMailTextFromMessage();
final future = widget.data.future;
if (future != null) {
_downloadAttachmentsFuture = future;
future.then((value) {
setState(() {
_downloadAttachmentsFuture = null;
});
});
}
super.didChangeDependencies();
}
@override
void dispose() {
_subjectController.dispose();
_plainTextController.dispose();
onSharedData = null;
super.dispose();
}
Future<String> _loadMailTextFromComposeData() =>
Future.value(widget.data.resumeText);
String get _signature => ref.read(settingsProvider.notifier).getSignatureHtml(
_from.account,
widget.data.action,
ref.text.localeName,
);
Future<String> _loadMailTextFromMessage() async {
final signature = _signature;
// find out signature:
final mb = widget.data.messageBuilder;
if (mb.originalMessage == null) {
if (_composeMode == ComposeMode.html) {
// cSpell:ignore nbsp
final html = '<p>${mb.text ?? ' '}</p>$signature';
return html;
} else {
return '${mb.text ?? ''}\n$signature';
}
} else {
const blockExternalImages = false;
final emptyMessageText = ref.text.composeEmptyMessage;
const maxImageWidth = 300;
if (widget.data.action == ComposeAction.newMessage) {
// continue with draft:
if (_composeMode == ComposeMode.html) {
final args = _HtmlGenerationArguments(
null,
mb.originalMessage,
blockExternalImages,
emptyMessageText,
maxImageWidth,
);
final html = await compute(_generateDraftHtmlImpl, args) + signature;
return html;
} else {
final text =
'${mb.originalMessage?.decodeTextPlainPart() ?? emptyMessageText}'
'\n$signature';
return text;
}
}
// TODO(RV): localize quote templates
final quoteTemplate = widget.data.action == ComposeAction.answer
? MailConventions.defaultReplyHeaderTemplate
: widget.data.action == ComposeAction.forward
? MailConventions.defaultForwardHeaderTemplate
: MailConventions.defaultReplyHeaderTemplate;
if (_composeMode == ComposeMode.html) {
final args = _HtmlGenerationArguments(
quoteTemplate,
mb.originalMessage,
blockExternalImages,
emptyMessageText,
maxImageWidth,
);
final html = await compute(_generateQuoteHtmlImpl, args) + signature;
return html;
} else {
final original = mb.originalMessage;
if (original != null) {
final header = MessageBuilder.fillTemplate(quoteTemplate, original);
final plainText = original.decodeTextPlainPart() ?? emptyMessageText;
final text = MessageBuilder.quotePlainText(header, plainText);
return '$text\n$signature';
} else {
return '\n$signature';
}
}
}
}
static String _generateQuoteHtmlImpl(_HtmlGenerationArguments args) {
final html = args.mimeMessage?.quoteToHtml(
quoteHeaderTemplate: args.quoteTemplate,
blockExternalImages: args.blockExternalImages,
emptyMessageText: args.emptyMessageText,
maxImageWidth: args.maxImageWidth,
);
return html ?? '';
}
static String _generateDraftHtmlImpl(_HtmlGenerationArguments args) {
final html = args.mimeMessage?.transformToHtml(
emptyMessageText: args.emptyMessageText,
maxImageWidth: args.maxImageWidth,
blockExternalImages: args.blockExternalImages,
);
return html ?? '';
}
Future<void> _populateMessageBuilder({
bool storeComposeDataForResume = false,
}) async {
final mb = widget.data.messageBuilder
..to = _toRecipients
..cc = _ccRecipients
..bcc = _bccRecipients
..subject = _subjectController.text;
final text = _composeMode == ComposeMode.html
? await _htmlEditorApi?.getText() ?? ''
: _plainTextController.text;
_resumeComposeData = widget.data.resume(text, composeMode: _composeMode);
if (storeComposeDataForResume) {
return;
} else {
if (_composeMode == ComposeMode.plainText) {
// create a plain text mail
if (mb.hasAttachments) {
final builder = mb.getTextPlainPart();
if (builder != null) {
builder.text = text;
} else {
mb.addTextPlain(text);
}
} else {
mb
..text = text
..setContentType(MediaType.textPlain);
}
} else {
// create a normal mail with an HTML and a plain text part:
final plainText = _convertToPlainText(text);
final multipartAlternativeBuilder = mb.hasAttachments
? mb.getPart(MediaSubtype.multipartAlternative, recursive: false) ??
mb.addPart(
mediaSubtype: MediaSubtype.multipartAlternative,
insert: true,
)
: mb;
if (!mb.hasAttachments) {
mb.setContentType(
MediaType.fromSubtype(MediaSubtype.multipartAlternative),
);
}
final plainTextBuilder = multipartAlternativeBuilder.getTextPlainPart();
if (plainTextBuilder != null) {
plainTextBuilder.text = plainText;
} else {
multipartAlternativeBuilder.addTextPlain(plainText);
}
final fullHtmlMessageText =
await _htmlEditorApi?.getFullHtml(content: text) ?? '';
final htmlTextBuilder = multipartAlternativeBuilder.getTextHtmlPart();
if (htmlTextBuilder != null) {
htmlTextBuilder.text = fullHtmlMessageText;
} else {
multipartAlternativeBuilder.addTextHtml(fullHtmlMessageText);
}
}
}
}
Future<MimeMessage> _buildMimeMessage(MailClient mailClient) async {
await _populateMessageBuilder();
widget.data.finalize();
final mb = widget.data.messageBuilder;
if (mailClient.account.hasAttribute(RealAccount.attributeBccMyself)) {
final myAddress = mailClient.account.fromAddress;
final myEmail = myAddress.email;
final bcc = mb.bcc;
if (bcc == null || !bcc.any((address) => address.email == myEmail)) {
if (bcc == null) {
mb.bcc = [myAddress];
} else {
bcc.add(myAddress);
}
}
}
final mimeMessage = mb.buildMimeMessage();
return mimeMessage;
}
MailClient _getMailClient() =>
ref.read(mailClientSourceProvider(account: _realAccount));
Future<void> _send(AppLocalizations localizations) async {
final subject = _subjectController.text.trim();
if (subject.isEmpty) {
final result = await LocalizedDialogHelper.askForConfirmation(
ref,
title: localizations.composeSubjectHint,
query: localizations.composeWarningNoSubject,
action: localizations.composeActionSentWithoutSubject,
);
if (result != true) {
return;
}
}
if (mounted) {
context.pop();
}
final mailClient = _getMailClient();
final mimeMessage = await _buildMimeMessage(mailClient);
try {
final append = !_from.account.addsSentMailAutomatically;
await mailClient.sendMessage(
mimeMessage,
from: _from.account.fromAddress,
appendToSent: append,
);
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.composeMailSendSuccess,
);
} catch (e, s) {
if (kDebugMode) {
print('Unable to send or append mail: $e $s');
}
// this state's context is now invalid because this widget is not
// mounted anymore
final currentContext = Routes.navigatorKey.currentContext;
if (currentContext != null && currentContext.mounted) {
final message =
(e is MailException) ? e.message ?? e.toString() : e.toString();
await LocalizedDialogHelper.showTextDialog(
ref,
localizations.errorTitle,
localizations.composeSendErrorInfo(message),
actions: [
PlatformTextButton(
onPressed: currentContext.pop,
child: Text(localizations.actionCancel),
),
PlatformTextButton(
child: Text(localizations.composeContinueEditingAction),
onPressed: () {
currentContext.pop();
_returnToCompose();
},
),
],
);
}
return;
}
final action = widget.data.action;
final storeFlags = action != ComposeAction.newMessage;
if (storeFlags) {
for (final originalMessage
in widget.data.originalMessages ?? const <Message?>[]) {
if (originalMessage == null) {
continue;
}
if (action == ComposeAction.answer) {
originalMessage.isAnswered = true;
} else {
originalMessage.isForwarded = true;
}
try {
await mailClient.store(
MessageSequence.fromMessage(originalMessage.mimeMessage),
originalMessage.mimeMessage.flags ?? [],
action: StoreAction.replace,
);
} catch (e, s) {
if (kDebugMode) {
print('Unable to update message flags: $e $s'); // otherwise ignore
}
}
}
} else if (widget.data.originalMessage?.mimeMessage
.hasFlag(MessageFlags.draft) ??
false) {
// delete draft message:
try {
final originalMessage = widget.data.originalMessage;
if (originalMessage != null) {
originalMessage.source.removeFromCache(originalMessage);
await mailClient.flagMessage(
originalMessage.mimeMessage,
isDeleted: true,
);
}
} catch (e, s) {
if (kDebugMode) {
print('Unable to update message flags: $e $s'); // otherwise ignore
}
}
}
}
@override
Widget build(BuildContext context) {
final localizations = ref.text;
final titleText = widget.data.action == ComposeAction.answer
? localizations.composeTitleReply
: widget.data.action == ComposeAction.forward
? localizations.composeTitleForward
: localizations.composeTitleNew;
final htmlEditorApi = _htmlEditorApi;
return WillPopScope(
onWillPop: () async {
await _populateMessageBuilder(storeComposeDataForResume: true);
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.composeLeftByMistake,
undo: _returnToCompose,
);
return Future.value(true);
},
// wait for https://github.com/flutter/flutter/issues/138525 before
// switching to PopScope
// onPopInvoked: (didPop) async {
// // let it pop but show snackbar to return:
// await _populateMessageBuilder(storeComposeDataForResume: true);
// ScaffoldMessengerService.instance.showTextSnackBar(
// localizations,
// localizations.composeLeftByMistake,
// undo: _returnToCompose,
// );
// },
child: PlatformScaffold(
material: (context, platform) =>
MaterialScaffoldData(drawer: const AppDrawer()),
body: CustomScrollView(
slivers: [
EnoughPlatformSliverAppBar(
title: Text(titleText),
pinned: true,
stretch: true,
actions: [
AddAttachmentPopupButton(
composeData: widget.data,
update: () => setState(
() {},
),
),
PlatformIconButton(
icon: const Icon(Icons.send),
onPressed: () => _send(localizations),
),
PlatformPopupMenuButton<_OverflowMenuChoice>(
onSelected: (result) {
switch (result) {
case _OverflowMenuChoice.showSourceCode:
_showSourceCode();
break;
case _OverflowMenuChoice.saveAsDraft:
_saveAsDraft();
break;
case _OverflowMenuChoice.requestReadReceipt:
_requestReadReceipt();
break;
case _OverflowMenuChoice.convertToPlainTextEditor:
_convertToPlainTextEditor();
break;
case _OverflowMenuChoice.convertToHtmlEditor:
_convertToHtmlEditor();
break;
}
},
itemBuilder: (context) => [
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.saveAsDraft,
child: Text(localizations.composeSaveDraftAction),
),
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.requestReadReceipt,
child:
Text(localizations.composeRequestReadReceiptAction),
),
if (_composeMode == ComposeMode.html)
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.convertToPlainTextEditor,
child: Text(
localizations.composeConvertToPlainTextEditorAction,
),
)
else
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.convertToHtmlEditor,
child: Text(
localizations.composeConvertToHtmlEditorAction,
),
),
if (ref.read(settingsProvider).enableDeveloperMode)
PlatformPopupMenuItem<_OverflowMenuChoice>(
value: _OverflowMenuChoice.showSourceCode,
child: Text(localizations.viewSourceAction),
),
],
),
], // actions
),
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
localizations.detailsHeaderFrom,
style: Theme.of(context).textTheme.bodySmall,
),
// SenderDropdown(
// from: widget.data.messageBuilder.from,
// onChanged:
PlatformDropdownButton<Sender>(
material: (context, platform) =>
MaterialDropdownButtonData(
isExpanded: true,
),
items: _senders
.map(
(s) => DropdownMenuItem<Sender>(
value: s,
child: Text(
s.toString(),
overflow: TextOverflow.fade,
),
),
)
.toList(),
onChanged: (s) async {
if (s != null) {
// (s) {
final builder = widget.data.messageBuilder
..from = [s.address];
final lastSignature = _signature;
_from = s;
final newSignature = _signature;
if (newSignature != lastSignature) {
await _htmlEditorApi?.replaceAll(
lastSignature,
newSignature,
);
}
if (_isReadReceiptRequested) {
builder.requestReadReceipt(
recipient: _from.address,
);
}
ref.read(currentAccountProvider.notifier).state =
s.account;
setState(() {
_realAccount = s.account;
});
await _checkAccountContactManager(_from.account);
}
},
value: _from,
hint: Text(localizations.composeSenderHint),
),
RecipientInputField(
contactManager: _from.account.contactManager,
addresses: _toRecipients,
autofocus: _focus == _Autofocus.to,
labelText: localizations.detailsHeaderTo,
hintText: localizations.composeRecipientHint,
additionalSuffixIcon: PlatformTextButton(
child: Text(localizations.detailsHeaderCc),
onPressed: () => setState(
() => _isCcBccVisible = !_isCcBccVisible,
),
),
),
if (_isCcBccVisible) ...[
RecipientInputField(
addresses: _ccRecipients,
contactManager: _from.account.contactManager,
labelText: localizations.detailsHeaderCc,
hintText: localizations.composeRecipientHint,
),
RecipientInputField(
addresses: _bccRecipients,
contactManager: _from.account.contactManager,
labelText: localizations.detailsHeaderBcc,
hintText: localizations.composeRecipientHint,
),
],
TextEditor(
controller: _subjectController,
autofocus: _focus == _Autofocus.subject,
decoration: InputDecoration(
labelText: localizations.composeSubjectLabel,
hintText: localizations.composeSubjectHint,
),
cupertinoShowLabel: false,
),
if (widget.data.messageBuilder.attachments.isNotEmpty ||
(_downloadAttachmentsFuture != null)) ...[
Padding(
padding: const EdgeInsets.only(top: 8),
child: AttachmentComposeBar(
composeData: widget.data,
isDownloading: _downloadAttachmentsFuture != null,
),
),
const Divider(
color: Colors.grey,
),
],
],
),
),
),
if (_isReadReceiptRequested)
SliverToBoxAdapter(
child: PlatformCheckboxListTile(
value: true,
title: Text(localizations.composeRequestReadReceiptAction),
onChanged: (value) {
_removeReadReceiptRequest();
},
),
),
if (_composeMode == ComposeMode.html && htmlEditorApi != null)
SliverHeaderHtmlEditorControls(
editorApi: htmlEditorApi,
suffix: EditorArtExtensionButton(editorApi: htmlEditorApi),
)
else if (_composeMode == ComposeMode.plainText &&
_plainTextEditorApi != null)
SliverHeaderTextEditorControls(
editorApi: _plainTextEditorApi,
),
SliverToBoxAdapter(
child: FutureBuilder<String>(
future: _loadMailTextFuture,
builder: (widget, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
return const Center(child: PlatformProgressIndicator());
case ConnectionState.done:
if (_composeMode == ComposeMode.html) {
final text = snapshot.data ?? '<p></p>';
return HtmlEditor(
onCreated: (api) {
setState(() {
_htmlEditorApi = api;
});
},
enableDarkMode:
Theme.of(context).brightness == Brightness.dark,
initialContent: text,
minHeight: 400,
);
} else {
// compose mode is plainText
_plainTextController.text = snapshot.data ?? '';
return Padding(
padding: const EdgeInsets.all(8),
child: TextEditor(
controller: _plainTextController,
minLines: 10,
maxLines: null,
onCreated: (api) {
setState(() {
_plainTextEditorApi = api;
});
},
),
);
}
}
},
),
),
],
),
),
);
}
Future<void> _showSourceCode() async {
final mailClient = _getMailClient();
final mime = await _buildMimeMessage(mailClient);
if (mounted) {
unawaited(context.pushNamed(Routes.sourceCode, extra: mime));
}
}
Future<void> _saveAsDraft() async {
context.pop();
final localizations = ref.text;
final mailClient = _getMailClient();
final mime = await _buildMimeMessage(mailClient);
try {
await mailClient.saveDraftMessage(mime);
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.composeMessageSavedAsDraft,
);
final originalMessage = widget.data.originalMessage;
if (originalMessage != null) {
await Future.delayed(const Duration(milliseconds: 20));
originalMessage.source.removeFromCache(originalMessage);
final originalMime = widget.data.messageBuilder.originalMessage;
if (originalMime != null && originalMime.hasFlag(MessageFlags.draft)) {
// delete previous draft message:
try {
await mailClient.flagMessage(originalMime, isDeleted: true);
} catch (e, s) {
if (kDebugMode) {
print('(ignored) unable to delete previous draft message $e $s');
}
}
}
}
} catch (e, s) {
if (kDebugMode) {
print('unable to save draft message $e $s');
}
final currentContext = Routes.navigatorKey.currentContext;
if (currentContext != null && currentContext.mounted) {
await LocalizedDialogHelper.showTextDialog(
ref,
localizations.errorTitle,
localizations.composeMessageSavedAsDraftErrorInfo(e.toString()),
actions: [
PlatformTextButton(
onPressed: currentContext.pop,
child: Text(localizations.actionCancel),
),
PlatformTextButton(
child: Text(localizations.composeContinueEditingAction),
onPressed: () {
currentContext.pop();
_returnToCompose();
},
),
],
);
}
}
}
void _requestReadReceipt() {
widget.data.messageBuilder.requestReadReceipt(recipient: _from.address);
setState(() {
_isReadReceiptRequested = true;
});
}
void _convertToPlainTextEditor() {
final future = _htmlEditorApi?.getText() ?? Future.value('');
setState(() {
_loadMailTextFuture = future.then(_convertToPlainText);
_composeMode = ComposeMode.plainText;
});
}
void _convertToHtmlEditor() {
final text = _plainTextController.text.replaceAll('\n', '<br/>');
setState(() {
_loadMailTextFuture = Future.value('<p>$text</p>');
_composeMode = ComposeMode.html;
});
}
void _removeReadReceiptRequest() {
widget.data.messageBuilder.removeReadReceiptRequest();
setState(() {
_isReadReceiptRequested = false;
});
}
void _returnToCompose() {
final currentContext = Routes.navigatorKey.currentContext;
if (currentContext != null && currentContext.mounted) {
currentContext.pushNamed(
Routes.mailCompose,
extra: _resumeComposeData,
);
}
}
Future<void> _checkAccountContactManager(RealAccount account) async {
final contactManager = account.contactManager;
if (contactManager == null) {
account.contactManager =
await ref.read(contactsLoaderProvider(account: account).future);
setState(() {});
}
}
Future _onSharedData(List<SharedData> sharedData) {
final firstData = sharedData.first;
if (firstData is SharedMailto) {
// TODO(RV): add the recipients, set the subject, set the text?
} else {
final api = _htmlEditorApi;
if (api != null) {
for (final data in sharedData) {
data
..addToMessageBuilder(widget.data.messageBuilder)
..addToEditor(api);
}
}
}
return Future.value();
}
String _convertToPlainText(String htmlText) =>
HtmlToPlainTextConverter.convert(htmlText);
}
class _HtmlGenerationArguments {
_HtmlGenerationArguments(
this.quoteTemplate,
this.mimeMessage,
this.blockExternalImages,
this.emptyMessageText,
this.maxImageWidth,
);
final String? quoteTemplate;
final MimeMessage? mimeMessage;
final bool blockExternalImages;
final String emptyMessageText;
final int maxImageWidth;
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/splash_screen.dart
|
import 'dart:math';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../localization/extension.dart';
import '../settings/theme/provider.dart';
/// Displays a splash screen
class SplashScreen extends ConsumerWidget {
/// Creates a new [SplashScreen]
const SplashScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final localizations = ref.text;
final texts = [
localizations.splashLoading1,
localizations.splashLoading2,
localizations.splashLoading3,
];
final index = Random().nextInt(texts.length);
final text = texts[index];
final timeOfDay = TimeOfDay.now();
final isNight = timeOfDay.hour >= 22 || timeOfDay.hour <= 6;
final splashColor =
isNight ? Colors.black87 : ref.watch(defaultColorSeedProvider);
final textColor = isNight
? Colors.white
: ThemeData.estimateBrightnessForColor(splashColor) == Brightness.dark
? Colors.white
: Colors.black87;
return PlatformScaffold(
body: Container(
color: splashColor,
child: Center(
child: Text(
text,
style: TextStyle(color: textColor, fontWeight: FontWeight.bold),
),
),
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/account_edit_screen.dart
|
import 'dart:async';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_platform_widgets/enough_platform_widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/model.dart';
import '../account/provider.dart';
import '../hoster/service.dart';
import '../localization/app_localizations.g.dart';
import '../localization/extension.dart';
import '../logger.dart';
import '../mail/provider.dart';
import '../routes/routes.dart';
import '../scaffold_messenger/service.dart';
import '../settings/provider.dart';
import '../settings/theme/icon_service.dart';
import '../util/localized_dialog_helper.dart';
import '../util/validator.dart';
import '../widgets/password_field.dart';
import '../widgets/signature.dart';
import 'base.dart';
/// The account edit screen
class AccountEditScreen extends HookConsumerWidget {
/// Creates a new account edit screen
const AccountEditScreen({super.key, required this.accountEmail});
/// The account to edit
final String accountEmail;
@override
Widget build(BuildContext context, WidgetRef ref) {
final account = ref.watch(
findRealAccountByEmailProvider(email: accountEmail),
);
if (account == null) {
return Center(child: PlatformCircularProgressIndicator());
}
final unifiedAccount = ref.watch(unifiedAccountProvider);
final localizations = ref.text;
final accountNameController = useTextEditingController(text: account.name);
final userNameController = useTextEditingController(text: account.userName);
final theme = Theme.of(context);
final iconService = IconService.instance;
final enableDeveloperMode = ref.watch(
settingsProvider.select((value) => value.enableDeveloperMode),
);
final isRetryingToConnectState = useState(false);
Future<void> saveAccounts() =>
ref.read(realAccountsProvider.notifier).save();
Widget buildEditContent() => SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8),
child: SafeArea(
child: ListenableBuilder(
listenable: account,
builder: (context, child) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (account.hasError) ...[
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
localizations
.editAccountFailureToConnectInfo(account.name),
),
),
if (isRetryingToConnectState.value)
const Padding(
padding: EdgeInsets.all(8),
child: PlatformProgressIndicator(),
)
else
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: PlatformTextButtonIcon(
onPressed: () => _reconnect(
context,
ref,
account,
account.mailAccount,
isRetryingToConnectState,
),
icon: Icon(iconService.retry),
label: Text(
localizations
.editAccountFailureToConnectRetryAction,
),
),
),
Expanded(
child: PlatformTextButton(
onPressed: () => _updateAuthentication(
context,
ref,
account,
isRetryingToConnectState,
),
child: Text(
localizations
.editAccountFailureToConnectChangePasswordAction,
),
),
),
],
),
const Divider(),
],
DecoratedPlatformTextField(
controller: accountNameController,
decoration: InputDecoration(
labelText: localizations.addAccountNameOfAccountLabel,
hintText: localizations.addAccountNameOfAccountHint,
),
onChanged: (value) async {
account.name = value;
await saveAccounts();
},
),
DecoratedPlatformTextField(
controller: userNameController,
decoration: InputDecoration(
labelText: localizations.addAccountNameOfUserLabel,
hintText: localizations.addAccountNameOfUserHint,
),
onChanged: (value) async {
account.userName = value;
await saveAccounts();
},
),
if (unifiedAccount != null)
PlatformCheckboxListTile(
value: !account.excludeFromUnified,
onChanged: (value) async {
final exclude = (value == false);
account.excludeFromUnified = exclude;
ref.invalidate(unifiedAccountProvider);
await saveAccounts();
},
title: Text(
localizations.editAccountIncludeInUnifiedLabel,
),
),
const Divider(),
Text(
localizations.signatureSettingsTitle,
style: theme.textTheme.titleMedium,
),
SignatureWidget(
account: account,
),
const Divider(),
Padding(
padding: const EdgeInsets.fromLTRB(8, 16, 8, 8),
child: Text(
localizations.editAccountAliasLabel(account.email),
),
),
if (account.hasNoAlias)
Padding(
padding: const EdgeInsets.all(8),
child: Text(
localizations.editAccountNoAliasesInfo,
style: const TextStyle(fontStyle: FontStyle.italic),
),
),
for (final alias in account.aliases)
Dismissible(
key: ValueKey(alias),
background: Container(
color: Colors.red,
child: Icon(iconService.messageActionDelete),
),
onDismissed: (direction) {
account.removeAlias(alias);
ScaffoldMessengerService.instance.showTextSnackBar(
localizations,
localizations.editAccountAliasRemoved(
alias.email,
),
);
ref.read(realAccountsProvider.notifier).save();
},
child: PlatformListTile(
title: Text(alias.toString()),
onTap: () {
showDialog(
context: context,
builder: (context) => _AliasEditDialog(
isNewAlias: false,
alias: alias,
account: account,
),
);
},
),
),
PlatformTextButtonIcon(
icon: Icon(iconService.add),
label: Text(localizations.editAccountAddAliasAction),
onPressed: () {
var email = account.email;
email = email.substring(email.lastIndexOf('@'));
final alias = MailAddress(account.userName, email);
showDialog(
context: context,
builder: (context) => _AliasEditDialog(
isNewAlias: true,
alias: alias,
account: account,
),
);
},
),
// section to test plus alias support
PlatformCheckboxListTile(
value: account.supportsPlusAliases,
onChanged: null,
title:
Text(localizations.editAccountPlusAliasesSupported),
),
PlatformTextButton(
child:
Text(localizations.editAccountCheckPlusAliasAction),
onPressed: () async {
final result = await showPlatformDialog<bool>(
context: context,
builder: (context) =>
_PlusAliasTestingDialog(account: account),
);
if (result != null) {
account
..supportsPlusAliases = result
..setAttribute(
RealAccount.attributePlusAliasTested,
true,
);
await saveAccounts();
}
},
),
Row(
children: [
Expanded(
child: PlatformCheckboxListTile(
value: account.bccMyself,
onChanged: (value) async {
final bccMyself = value ?? false;
account.bccMyself = bccMyself;
await saveAccounts();
},
title: Text(localizations.editAccountBccMyself),
),
),
PlatformIconButton(
icon: Icon(CommonPlatformIcons.info),
onPressed: () => LocalizedDialogHelper.showTextDialog(
ref,
localizations.editAccountBccMyselfDescriptionTitle,
localizations.editAccountBccMyselfDescriptionText,
),
),
],
),
const Divider(),
PlatformTextButtonIcon(
onPressed: () => context.pushNamed(
Routes.accountServerDetails,
pathParameters: {
Routes.pathParameterEmail: account.email,
},
),
icon: const Icon(Icons.edit),
label:
Text(localizations.editAccountServerSettingsAction),
),
const Divider(),
Padding(
padding: const EdgeInsets.only(top: 16),
child: PlatformTextButtonIcon(
backgroundColor: Colors.red,
style:
TextButton.styleFrom(backgroundColor: Colors.red),
icon: const Icon(
Icons.delete,
color: Colors.white,
),
label: Text(
localizations.editAccountDeleteAccountAction,
style:
Theme.of(context).textTheme.labelLarge?.copyWith(
color: Colors.white,
),
),
onPressed: () async {
final result =
await LocalizedDialogHelper.askForConfirmation(
ref,
title: localizations
.editAccountDeleteAccountConfirmationTitle,
query: localizations
.editAccountDeleteAccountConfirmationQuery(
accountNameController.text,
),
action: localizations.actionDelete,
isDangerousAction: true,
);
if (result ?? false) {
if (!context.mounted) {
return;
}
ref
.read(realAccountsProvider.notifier)
.removeAccount(account);
if (ref.read(realAccountsProvider).isEmpty) {
context.goNamed(Routes.welcome);
} else {
context.goNamed(Routes.mail);
}
}
},
),
),
if (enableDeveloperMode) ...[
const Divider(),
Padding(
padding: const EdgeInsets.only(top: 16),
child: PlatformCheckboxListTile(
value: account.enableLogging,
title: Text(localizations.editAccountEnableLogging),
onChanged: (value) {
if (value != null) {
account.enableLogging = value;
ref.read(realAccountsProvider.notifier).save();
final message = value
? localizations.editAccountLoggingEnabled
: localizations.editAccountLoggingDisabled;
ScaffoldMessengerService.instance
.showTextSnackBar(localizations, message);
}
},
),
),
],
],
),
),
),
),
);
return BasePage(
title: localizations.editAccountTitle(account.name),
subtitle: account.email,
content: buildEditContent(),
);
}
Future<void> _updateAuthentication(
BuildContext context,
WidgetRef ref,
RealAccount account,
ValueNotifier<bool> isRetryingToConnectState,
) async {
// TODO(RV): find solution to disconnect possibly connected account
// unawaited(mailService.disconnect(account));
final authentication = account.mailAccount.incoming.authentication;
if (authentication is PlainAuthentication) {
// simple case: password is directly given,
// can be edited and account can be updated
final mutableAuth = _MutablePlainAuthentication(
password: authentication.password,
userName: authentication.userName,
);
final result = await LocalizedDialogHelper.showWidgetDialog(
ref,
_PasswordUpdateDialog(
authentication: mutableAuth,
),
defaultActions: DialogActions.okAndCancel,
);
if (result == true) {
final mailAccount = account.mailAccount;
final outgoingAuth = mailAccount.outgoing.authentication;
var updatedMailAccount = mailAccount.copyWith(
incoming: mailAccount.incoming.copyWith(
authentication: authentication.copyWith(
password: mutableAuth.password,
),
),
);
if (outgoingAuth is PlainAuthentication) {
updatedMailAccount = mailAccount.copyWith(
outgoing: mailAccount.outgoing.copyWith(
authentication: outgoingAuth.copyWith(
password: mutableAuth.password,
),
),
);
}
if (context.mounted) {
await _reconnect(
context,
ref,
account,
updatedMailAccount,
isRetryingToConnectState,
);
}
}
} else if (authentication is OauthAuthentication) {
// oauth case: restart oauth authentication,
// save new token
final hoster = MailHosterService
.instance[account.mailAccount.incoming.serverConfig.hostname];
final oauthClient = hoster?.oauthClient;
if (hoster != null && oauthClient != null) {
final token = await oauthClient.authenticate(account.mailAccount.email);
if (token != null) {
final adaptedIncomingAuth = authentication.copyWith(
userName: account.email,
token: token,
);
final outgoingAuth = account.mailAccount.outgoing.authentication;
var adaptedOutgoingAuth = outgoingAuth;
if (outgoingAuth is OauthAuthentication) {
adaptedOutgoingAuth = outgoingAuth.copyWith(
userName: account.email,
token: token,
);
}
final mailAccount = account.mailAccount;
final updatedMailAccount = mailAccount.copyWith(
incoming: mailAccount.incoming
.copyWith(authentication: adaptedIncomingAuth),
outgoing: mailAccount.outgoing
.copyWith(authentication: adaptedOutgoingAuth),
);
if (context.mounted) {
await _reconnect(
context,
ref,
account,
updatedMailAccount,
isRetryingToConnectState,
);
}
}
}
}
}
Future<bool> _reconnect(
BuildContext context,
WidgetRef ref,
RealAccount account,
MailAccount mailAccount,
ValueNotifier<bool> isRetryingToConnectState,
) async {
isRetryingToConnectState.value = true;
try {
final accountCopy = account.copyWith(mailAccount: mailAccount);
final connectedAccount = await ref.read(
firstTimeMailClientSourceProvider(
account: accountCopy,
).future,
);
if (connectedAccount == null ||
!connectedAccount.mailClient.isConnected) {
throw Exception(
'Unable to connect',
);
}
ref
.read(realAccountsProvider.notifier)
.replaceAccount(oldAccount: account, newAccount: connectedAccount);
isRetryingToConnectState.value = false;
if (context.mounted) {
final localizations = ref.text;
await LocalizedDialogHelper.showTextDialog(
ref,
localizations.editAccountFailureToConnectFixedTitle,
localizations.editAccountFailureToConnectFixedInfo,
);
}
if (!account.excludeFromUnified) {
ref.invalidate(unifiedAccountProvider);
}
return true;
} catch (e) {
logger.e('Unable to reconnect account: $e');
isRetryingToConnectState.value = false;
if (context.mounted) {
final localizations = ref.text;
await LocalizedDialogHelper.showTextDialog(
ref,
localizations.errorTitle,
localizations.editAccountFailureToConnectInfo(account.name),
);
}
return false;
}
}
}
class _MutablePlainAuthentication {
_MutablePlainAuthentication({
required this.userName,
required this.password,
});
String userName;
String password;
}
class _PasswordUpdateDialog extends StatefulHookConsumerWidget {
const _PasswordUpdateDialog({
required this.authentication,
});
final _MutablePlainAuthentication authentication;
@override
ConsumerState createState() => _PasswordUpdateDialogState();
}
class _PasswordUpdateDialogState extends ConsumerState<_PasswordUpdateDialog> {
late TextEditingController _controller;
@override
void initState() {
_controller = TextEditingController(text: widget.authentication.password);
super.initState();
}
@override
Widget build(BuildContext context) => PasswordField(
controller: _controller,
labelText: ref.text.accountDetailsPasswordLabel,
onChanged: (text) => widget.authentication.password = text,
);
}
class _PlusAliasTestingDialog extends StatefulHookConsumerWidget {
const _PlusAliasTestingDialog({required this.account});
final RealAccount account;
@override
ConsumerState<_PlusAliasTestingDialog> createState() =>
_PlusAliasTestingDialogState();
}
class _PlusAliasTestingDialogState
extends ConsumerState<_PlusAliasTestingDialog> {
bool _isContinueAvailable = true;
int _step = 0;
static const int _maxStep = 1;
late String _generatedAliasAddress;
// MimeMessage? _testMessage;
MailClient? _mailClient;
@override
void initState() {
_generatedAliasAddress = generateRandomPlusAlias(widget.account);
super.initState();
}
bool _filter(MailEvent event) {
if (event is MailLoadEvent) {
final msg = event.message;
final to = msg.to;
if (to != null &&
to.length == 1 &&
to.first.email == _generatedAliasAddress) {
// this is the test message, plus aliases are supported
widget.account.supportsPlusAliases = true;
setState(() {
_isContinueAvailable = true;
_step++;
});
_deleteMessage(event.mailClient, msg);
return true;
} else if ((msg.getHeaderValue('auto-submitted') != null) &&
(msg.isTextPlainMessage()) &&
(msg.decodeContentText()?.contains(_generatedAliasAddress) ??
false)) {
// this is an automatic reply telling that the address is not available
setState(() {
_isContinueAvailable = true;
_step++;
});
_deleteMessage(event.mailClient, msg);
return true;
}
}
return false;
}
Future<void> _deleteMessage(MailClient mailClient, MimeMessage msg) async {
await mailClient.flagMessage(msg, isDeleted: true);
}
@override
void dispose() {
super.dispose();
_mailClient?.removeEventFilter(_filter);
_mailClient?.disconnect();
}
@override
Widget build(BuildContext context) {
final localizations = ref.text;
return PlatformAlertDialog(
title: Text(
localizations.editAccountTestPlusAliasTitle(widget.account.name),
),
content: SizedBox(
width: double.maxFinite,
child: PlatformStepper(
onStepCancel: _step == 3 ? null : () => context.pop(),
onStepContinue: !_isContinueAvailable
? null
: () async {
if (_step < _maxStep) {
_step++;
} else {
context.pop(
widget.account.supportsPlusAliases,
);
}
switch (_step) {
case 1:
setState(() {
_isContinueAvailable = false;
});
// send the email and wait for a response:
final msg = MessageBuilder.buildSimpleTextMessage(
widget.account.fromAddress,
[MailAddress(null, _generatedAliasAddress)],
'This is an automated message testing support '
'for + aliases. Please ignore.',
subject: 'Testing + Alias',
);
// _testMessage = msg;
final mailClient = ref.read(
mailClientSourceProvider(account: widget.account),
);
_mailClient = mailClient;
mailClient.addEventFilter(_filter);
await mailClient.sendMessage(msg, appendToSent: false);
break;
}
},
steps: [
Step(
title: Text(
localizations.editAccountTestPlusAliasStepIntroductionTitle,
),
content: Text(
localizations.editAccountTestPlusAliasStepIntroductionText(
widget.account.name,
_generatedAliasAddress,
),
style: const TextStyle(fontSize: 12),
),
isActive: _step == 0,
),
Step(
title:
Text(localizations.editAccountTestPlusAliasStepTestingTitle),
content: const Center(child: PlatformProgressIndicator()),
isActive: _step == 1,
),
Step(
title:
Text(localizations.editAccountTestPlusAliasStepResultTitle),
content: widget.account.supportsPlusAliases
? Text(
localizations.editAccountTestPlusAliasStepResultSuccess(
widget.account.name,
),
)
: Text(
localizations.editAccountTestPlusAliasStepResultNoSuccess(
widget.account.name,
),
),
isActive: _step == 3,
state: StepState.complete,
),
],
currentStep: _step,
),
),
);
}
/// Creates a new random plus alias based on the primary email address
/// of the [account].
String generateRandomPlusAlias(RealAccount account) {
final mail = account.email;
final atIndex = mail.lastIndexOf('@');
if (atIndex == -1) {
throw StateError(
'unable to create alias based on invalid email <$mail>.',
);
}
final random = MessageBuilder.createRandomId(length: 8);
return '${mail.substring(0, atIndex)}+$random${mail.substring(atIndex)}';
}
}
class _AliasEditDialog extends StatefulHookConsumerWidget {
const _AliasEditDialog({
required this.isNewAlias,
required this.alias,
required this.account,
});
final MailAddress alias;
final RealAccount account;
final bool isNewAlias;
@override
ConsumerState<_AliasEditDialog> createState() => _AliasEditDialogState();
}
class _AliasEditDialogState extends ConsumerState<_AliasEditDialog> {
late TextEditingController _nameController;
late TextEditingController _emailController;
late bool _isEmailValid;
String? _errorMessage;
bool _isSaving = false;
@override
void initState() {
_nameController = TextEditingController(text: widget.alias.personalName);
_emailController = TextEditingController(text: widget.alias.email);
_isEmailValid = !widget.isNewAlias;
super.initState();
}
@override
Widget build(BuildContext context) {
final localizations = ref.text;
return PlatformAlertDialog(
title: Text(widget.isNewAlias
? localizations.editAccountAddAliasTitle
: localizations.editAccountEditAliasTitle),
content: _isSaving
? const PlatformProgressIndicator()
: _buildContent(localizations),
actions: [
PlatformTextButton(
child: Text(localizations.actionCancel),
onPressed: () => context.pop(),
),
PlatformTextButton(
onPressed: _isEmailValid
? () {
setState(() {
_isSaving = true;
});
final alias = widget.alias.copyWith(
email: _emailController.text,
personalName: _nameController.text,
);
widget.account.addAlias(alias);
ref.read(realAccountsProvider.notifier).save();
context.pop();
}
: null,
child: Text(
widget.isNewAlias
? localizations.editAccountAliasAddAction
: localizations.editAccountAliasUpdateAction,
),
),
],
);
}
Widget _buildContent(AppLocalizations localizations) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
DecoratedPlatformTextField(
controller: _nameController,
decoration: InputDecoration(
labelText: localizations.editAccountEditAliasNameLabel,
hintText: localizations.addAccountNameOfUserHint,
),
),
DecoratedPlatformTextField(
controller: _emailController,
decoration: InputDecoration(
labelText: localizations.editAccountEditAliasEmailLabel,
hintText: localizations.editAccountEditAliasEmailHint,
),
onChanged: (value) {
final bool isValid = Validator.validateEmail(value);
final emailValue = value.toLowerCase();
if (isValid) {
final existingAlias = widget.account.aliases.firstWhereOrNull(
(e) => e.email.toLowerCase() == emailValue,
);
if (existingAlias != null && existingAlias != widget.alias) {
setState(() {
_errorMessage =
localizations.editAccountEditAliasDuplicateError(value);
});
} else if (_errorMessage != null) {
setState(() {
_errorMessage = null;
});
}
}
if (isValid != _isEmailValid) {
setState(() {
_isEmailValid = isValid;
});
}
},
),
if (_errorMessage != null)
Padding(
padding: const EdgeInsets.all(8),
child: Text(
_errorMessage ?? '',
style: const TextStyle(
color: Colors.red,
fontStyle: FontStyle.italic,
),
),
),
],
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/mail_screen.dart
|
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_platform_widgets/platform.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../account/model.dart';
import '../account/provider.dart';
import '../localization/extension.dart';
import '../mail/provider.dart';
import '../routes/routes.dart';
import 'base.dart';
import 'error_screen.dart';
import 'screens.dart';
/// Displays the mail for a given account
class MailScreen extends HookConsumerWidget {
/// Creates a [MailScreen]
const MailScreen({
super.key,
required this.account,
this.mailbox,
this.showSplashWhileLoading = false,
});
/// The account to display
final Account account;
/// The optional mailbox
final Mailbox? mailbox;
/// Should the splash screen shown while loading the message source?
final bool showSplashWhileLoading;
@override
Widget build(BuildContext context, WidgetRef ref) {
final text = ref.text;
final sourceFuture = ref.watch(
sourceProvider(
account: account,
mailbox: mailbox,
),
);
if (useAppDrawerAsRoot) {
// when the app drawer is below in the widget tree,
// set the account and mailbox:
useMemoized(() async {
await Future.delayed(const Duration(milliseconds: 10));
ref.read(currentAccountProvider.notifier).state = account;
ref.read(currentMailboxProvider.notifier).state = mailbox;
});
}
final title =
account is UnifiedAccount ? text.unifiedAccountName : account.name;
final subtitle = account.fromAddress.email;
return ProviderScope(
overrides: [
currentMailboxProvider.overrideWith((ref) => mailbox),
currentAccountProvider.overrideWith((ref) => account),
],
child: sourceFuture.when(
loading: () => showSplashWhileLoading
? const SplashScreen()
: BasePage(
title: title,
subtitle: subtitle,
content: const Center(
child: PlatformProgressIndicator(),
),
),
error: (error, stack) => ErrorScreen(
error: error,
stackTrace: stack,
),
data: (source) => MessageSourceScreen(messageSource: source),
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/sourcecode_screen.dart
|
import 'package:enough_mail/mime.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'base.dart';
class SourceCodeScreen extends StatelessWidget {
const SourceCodeScreen({super.key, required this.mimeMessage});
final MimeMessage mimeMessage;
@override
Widget build(BuildContext context) {
String? sizeText;
if (mimeMessage.size != null) {
final sizeFormat = NumberFormat('###.0#');
final sizeKb = (mimeMessage.size ?? 0) / 1024;
final sizeMb = sizeKb / 1024;
sizeText = sizeMb > 1
? 'Size: ${sizeFormat.format(sizeKb)} kb / ${sizeFormat.format(sizeMb)} mb'
: 'Size: ${sizeFormat.format(sizeKb)} kb / ${mimeMessage.size} bytes';
}
return BasePage(
title: mimeMessage.decodeSubject() ?? '<no subject>',
content: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SelectableText('ID: ${mimeMessage.sequenceId}'),
SelectableText('UID: ${mimeMessage.uid}'),
if (sizeText != null) SelectableText(sizeText),
if (mimeMessage.body != null)
SelectableText('BODY: ${mimeMessage.body}'),
Divider(
color: Theme.of(context).colorScheme.secondary,
thickness: 1,
height: 16,
),
SelectableText(mimeMessage.renderMessage()),
],
),
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/screens/message_details_screen_for_notification.dart
|
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../mail/provider.dart';
import '../notification/model.dart';
import 'error_screen.dart';
import 'message_details_screen.dart';
/// Displays the message details for a notification
class MessageDetailsForNotificationScreen extends ConsumerWidget {
/// Creates a [MessageDetailsForNotificationScreen]
const MessageDetailsForNotificationScreen({
super.key,
required this.payload,
this.blockExternalContent = false,
});
/// The payload of the notification
final MailNotificationPayload payload;
/// Whether to block external content
final bool blockExternalContent;
@override
Widget build(BuildContext context, WidgetRef ref) {
final messageValue = ref.watch(
singleMessageLoaderProvider(payload: payload),
);
return messageValue.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stack) => ErrorScreen(error: error, stackTrace: stack),
data: (data) => MessageDetailsScreen(
message: data,
blockExternalContent: blockExternalContent,
),
);
}
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/localization/extension.dart
|
import 'dart:io';
import 'package:enough_icalendar/enough_icalendar.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:intl/date_symbol_data_local.dart' as date_intl;
import 'package:intl/date_symbols.dart';
import 'package:intl/intl.dart';
import '../util/date_helper.dart';
import 'app_localizations.g.dart';
import 'provider.dart';
// lateDateFormat _dateTimeFormatToday;
// late intl.DateFormat _dateTimeFormatLastWeek;
// late intl.DateFormat _dateTimeFormat;
// late intl.DateFormat _dateTimeFormatLong;
// late intl.DateFormat _dateFormatDayInLastWeek;
// late intl.DateFormat _dateFormatDayBeforeLastWeek;
// late intl.DateFormat _dateFormatLong;
// late intl.DateFormat _dateFormatShort;
// // late intl.DateFormat _dateFormatMonth;
// late intl.DateFormat _dateFormatWeekday;
// // late intl.DateFormat _dateFormatNoTime;
/// Allows to look up the localized strings for the current locale
extension AppLocalizationRef on Ref {
/// Retrieves the current localizations
AppLocalizations get text => read(currentAppLocalizationProvider);
}
/// Allows to look up the localized strings for the current locale
extension AppLocalizationWidgetRef on WidgetRef {
/// Retrieves the current localizations
AppLocalizations get text => read(currentAppLocalizationProvider);
/// Retrieves the data range Name
String getDateRangeName(
DateSectionRange range,
) {
final localizations = text;
switch (range) {
case DateSectionRange.future:
return localizations.dateRangeFuture;
case DateSectionRange.tomorrow:
return localizations.dateRangeTomorrow;
case DateSectionRange.today:
return localizations.dateRangeToday;
case DateSectionRange.yesterday:
return localizations.dateRangeYesterday;
case DateSectionRange.thisWeek:
return localizations.dateRangeCurrentWeek;
case DateSectionRange.lastWeek:
return localizations.dateRangeLastWeek;
case DateSectionRange.thisMonth:
return localizations.dateRangeCurrentMonth;
case DateSectionRange.monthOfThisYear:
return localizations.dateRangeCurrentYear;
case DateSectionRange.monthAndYear:
return localizations.dateRangeLongAgo;
}
}
DateFormat get _dateTimeFormatLong =>
// cSpell: ignore yMMMMEEEEd
DateFormat.yMMMMEEEEd(text.localeName).add_jm();
DateFormat get _dateTimeFormatLastWeek =>
DateFormat.E(text.localeName).add_jm();
DateFormat get _dateFormatDayInLastWeek => DateFormat.E(text.localeName);
DateFormat get _dateFormatDayBeforeLastWeek =>
DateFormat.yMd(text.localeName);
DateFormat get _dateFormatLong => DateFormat.yMMMMEEEEd(text.localeName);
DateFormat get _dateFormatShort => DateFormat.yMd(text.localeName);
DateFormat get _dateFormatWeekday => DateFormat.EEEE(text.localeName);
DateFormat get _dateTimeFormatToday => DateFormat.jm(text.localeName);
DateFormat get _dateTimeFormat => DateFormat.yMd(text.localeName).add_jm();
String formatDateTime(
DateTime? dateTime, {
bool alwaysUseAbsoluteFormat = false,
bool useLongFormat = false,
}) {
if (dateTime == null) {
return text.dateUndefined;
}
if (alwaysUseAbsoluteFormat) {
if (useLongFormat) {
return _dateTimeFormatLong.format(dateTime);
}
return _dateTimeFormat.format(dateTime);
}
final nw = DateTime.now();
final today = nw.subtract(
Duration(
hours: nw.hour,
minutes: nw.minute,
seconds: nw.second,
milliseconds: nw.millisecond,
),
);
final lastWeek = today.subtract(const Duration(days: 7));
String date;
if (dateTime.isAfter(today)) {
date = _dateTimeFormatToday.format(dateTime);
} else if (dateTime.isAfter(lastWeek)) {
date = _dateTimeFormatLastWeek.format(dateTime);
} else {
date = useLongFormat
? _dateTimeFormatLong.format(dateTime)
: _dateTimeFormat.format(dateTime);
}
return date;
}
String formatDate(DateTime? dateTime, {bool useLongFormat = false}) {
if (dateTime == null) {
return text.dateUndefined;
}
return useLongFormat
? _dateFormatLong.format(dateTime)
: _dateFormatShort.format(dateTime);
}
String formatDay(DateTime dateTime) {
final messageDate = dateTime;
final nw = DateTime.now();
final today = nw.subtract(
Duration(
hours: nw.hour,
minutes: nw.minute,
seconds: nw.second,
milliseconds: nw.millisecond,
),
);
if (messageDate.isAfter(today)) {
return text.dateDayToday;
} else if (messageDate.isAfter(today.subtract(const Duration(days: 1)))) {
return text.dateDayYesterday;
} else if (messageDate.isAfter(today.subtract(const Duration(days: 7)))) {
return text
.dateDayLastWeekday(_dateFormatDayInLastWeek.format(messageDate));
} else {
return _dateFormatDayBeforeLastWeek.format(messageDate);
}
}
String formatWeekDay(DateTime dateTime) =>
_dateFormatWeekday.format(dateTime);
List<WeekDay> formatWeekDays({int? startOfWeekDay, bool abbreviate = false}) {
final dateSymbols = date_intl.dateTimeSymbolMap()[text.localeName];
final weekdays = (dateSymbols is DateSymbols)
? (abbreviate
// cSpell: ignore STANDALONESHORTWEEKDAYS, STANDALONEWEEKDAYS
? dateSymbols.STANDALONESHORTWEEKDAYS
: dateSymbols.STANDALONEWEEKDAYS)
: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
final usedStartOfWeekDay = startOfWeekDay ?? firstDayOfWeek;
final result = <WeekDay>[];
for (int i = 0; i < 7; i++) {
final day = ((usedStartOfWeekDay + i) <= 7)
? (usedStartOfWeekDay + i)
: ((usedStartOfWeekDay + i) - 7);
final nameIndex = day == DateTime.sunday ? 0 : day;
final name = weekdays[nameIndex];
result.add(WeekDay(day, name));
}
return result;
}
Locale _getPlatformLocale() {
final localeName = Platform.localeName;
final parts = localeName.split('_');
final languageCode = parts.first;
final countryCode = parts.length > 1 ? parts[1].split('.').first : null;
return Locale(languageCode, countryCode);
}
static int? _firstDayOfWeek;
int get firstDayOfWeek {
final value = _firstDayOfWeek;
if (value != null) {
return value;
}
final locale = _getPlatformLocale();
final firstDay =
_firstDayOfWeekPerCountryCode[locale.countryCode] ?? DateTime.monday;
_firstDayOfWeek = firstDay;
return firstDay;
}
String? formatMemory(int? size) {
if (size == null) {
return null;
}
double sizeD = size + 0.0;
final units = ['gb', 'mb', 'kb', 'bytes'];
var unitIndex = units.length - 1;
while ((sizeD / 1024) > 1.0 && unitIndex > 0) {
sizeD = sizeD / 1024;
unitIndex--;
}
final sizeFormat = NumberFormat('###.0#', text.localeName);
return '${sizeFormat.format(sizeD)} ${units[unitIndex]}';
}
String formatIsoDuration(IsoDuration duration) {
final localizations = text;
final buffer = StringBuffer();
if (duration.isNegativeDuration) {
buffer.write('-');
}
if (duration.years > 0) {
buffer.write(localizations.durationYears(duration.years));
}
if (duration.months > 0) {
if (buffer.isNotEmpty) buffer.write(', ');
buffer.write(localizations.durationMonths(duration.months));
}
if (duration.weeks > 0) {
if (buffer.isNotEmpty) buffer.write(', ');
buffer.write(localizations.durationWeeks(duration.weeks));
}
if (duration.days > 0) {
if (buffer.isNotEmpty) buffer.write(', ');
buffer.write(localizations.durationDays(duration.days));
}
if (duration.hours > 0) {
if (buffer.isNotEmpty) buffer.write(', ');
buffer.write(localizations.durationHours(duration.hours));
}
if (duration.minutes > 0) {
if (buffer.isNotEmpty) buffer.write(', ');
buffer.write(localizations.durationHours(duration.minutes));
}
if (buffer.isEmpty) {
buffer.write(localizations.durationEmpty);
}
return buffer.toString();
}
}
extension AppLocalizationExtension on BuildContext {
String formatTimeOfDay(TimeOfDay timeOfDay) => timeOfDay.format(this);
}
class WeekDay {
const WeekDay(this.day, this.name);
final int day;
final String name;
}
/// Day of week for countries (in two letter code) for
/// which the week does not start on Monday
///
/// Source: http://chartsbin.com/view/41671
const _firstDayOfWeekPerCountryCode = <String, int>{
'ae': DateTime.saturday, // United Arab Emirates
'af': DateTime.saturday, // Afghanistan
'ar': DateTime.sunday, // Argentina
'bh': DateTime.saturday, // Bahrain
'br': DateTime.sunday, // Brazil
'bz': DateTime.sunday, // Belize
'bo': DateTime.sunday, // Bolivia
'ca': DateTime.sunday, // Canada
'cl': DateTime.sunday, // Chile
'cn': DateTime.sunday, // China
'co': DateTime.sunday, // Colombia
// cSpell: ignore Rica
'cr': DateTime.sunday, // Costa Rica
'do': DateTime.sunday, // Dominican Republic
'dz': DateTime.saturday, // Algeria
'ec': DateTime.sunday, // Ecuador
'eg': DateTime.saturday, // Egypt
'gt': DateTime.sunday, // Guatemala
'hk': DateTime.sunday, // Hong Kong
'hn': DateTime.sunday, // Honduras
'il': DateTime.sunday, // Israel
'iq': DateTime.saturday, // Iraq
'ir': DateTime.saturday, // Iran
'jm': DateTime.sunday, // Jamaica
'io': DateTime.saturday, // Jordan
'jp': DateTime.sunday, // Japan
'ke': DateTime.sunday, // Kenya
'kr': DateTime.sunday, // South Korea
'kw': DateTime.saturday, // Kuwait
'ly': DateTime.saturday, // Libya
'mo': DateTime.sunday, // Macao
'mx': DateTime.sunday, // Mexico
'ni': DateTime.sunday, // Nicaragua
'om': DateTime.saturday, // Oman
'pa': DateTime.sunday, // Panama
'pe': DateTime.sunday, // Peru
'ph': DateTime.sunday, // Philippines
'pr': DateTime.sunday, // Puerto Rico
'qa': DateTime.saturday, // Qatar
'sa': DateTime.saturday, // Saudi Arabia
'sv': DateTime.sunday, // El Salvador
'sy': DateTime.saturday, // Syria
'tw': DateTime.sunday, // Taiwan
'us': DateTime.sunday, // USA
've': DateTime.sunday, // Venezuela
'ye': DateTime.saturday, // Yemen
'za': DateTime.sunday, // South Africa
'zw': DateTime.sunday, // Zimbabwe
};
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/localization/app_localizations_en.g.dart
|
import 'package:intl/intl.dart' as intl;
import 'app_localizations.g.dart';
/// The translations for English (`en`).
class AppLocalizationsEn extends AppLocalizations {
AppLocalizationsEn([String locale = 'en']) : super(locale);
@override
String get signature => 'Sent with Maily';
@override
String get actionCancel => 'Cancel';
@override
String get actionOk => 'OK';
@override
String get actionDone => 'Done';
@override
String get actionNext => 'Next';
@override
String get actionSkip => 'Skip';
@override
String get actionUndo => 'Undo';
@override
String get actionDelete => 'Delete';
@override
String get actionAccept => 'Accept';
@override
String get actionDecline => 'Decline';
@override
String get actionEdit => 'Edit';
@override
String get actionAddressCopy => 'Copy';
@override
String get actionAddressCompose => 'New message';
@override
String get actionAddressSearch => 'Search';
@override
String get splashLoading1 => 'Maily starting...';
@override
String get splashLoading2 => 'Getting your Maily engine ready...';
@override
String get splashLoading3 => 'Launching Maily in 10, 9, 8...';
@override
String get welcomePanel1Title => 'Maily';
@override
String get welcomePanel1Text => 'Welcome to Maily, your friendly and fast email helper!';
@override
String get welcomePanel2Title => 'Accounts';
@override
String get welcomePanel2Text => 'Manage unlimited email accounts. Read and search for mails in all your accounts at once.';
@override
String get welcomePanel3Title => 'Swipe & Long-Press';
@override
String get welcomePanel3Text => 'Swipe your mails to delete them or to mark them read. Long-press a message to select and manage several messages.';
@override
String get welcomePanel4Title => 'Keep your Inbox clean';
@override
String get welcomePanel4Text => 'Unsubscribe newsletters with just one tap.';
@override
String get welcomeActionSignIn => 'Sign in to your mail account';
@override
String get homeSearchHint => 'Your search';
@override
String get homeActionsShowAsStack => 'Show as stack';
@override
String get homeActionsShowAsList => 'Show as list';
@override
String get homeEmptyFolderMessage => 'All done!\n\nThere are no messages in this folder.';
@override
String get homeEmptySearchMessage => 'No messages found.';
@override
String get homeDeleteAllTitle => 'Confirm';
@override
String get homeDeleteAllQuestion => 'Really delete all messages?';
@override
String get homeDeleteAllAction => 'Delete all';
@override
String get homeDeleteAllScrubOption => 'Scrub messages';
@override
String get homeDeleteAllSuccess => 'All messages deleted.';
@override
String get homeMarkAllSeenAction => 'All read';
@override
String get homeMarkAllUnseenAction => 'All unread';
@override
String get homeFabTooltip => 'New message';
@override
String get homeLoadingMessageSourceTitle => 'Loading...';
@override
String homeLoading(String name) {
return 'loading $name...';
}
@override
String get swipeActionToggleRead => 'Mark as read/unread';
@override
String get swipeActionDelete => 'Delete';
@override
String get swipeActionMarkJunk => 'Mark as junk';
@override
String get swipeActionArchive => 'Archive';
@override
String get swipeActionFlag => 'Toggle flag';
@override
String multipleMovedToJunk(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Marked $numberString messages as junk',
one: 'One message marked as junk',
);
return '$_temp0';
}
@override
String multipleMovedToInbox(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Moved $numberString messages to inbox',
one: 'Moved one message to inbox',
);
return '$_temp0';
}
@override
String multipleMovedToArchive(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Archived $numberString messages',
one: 'Archived one message',
);
return '$_temp0';
}
@override
String multipleMovedToTrash(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Deleted $numberString messages',
one: 'Deleted one message',
);
return '$_temp0';
}
@override
String get multipleSelectionNeededInfo => 'Please select messages first.';
@override
String multipleSelectionActionFailed(String details) {
return 'Unable to perform action\nDetails: $details';
}
@override
String multipleMoveTitle(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Move $numberString messages',
one: 'Move message',
);
return '$_temp0';
}
@override
String get messageActionMultipleMarkSeen => 'Mark as read';
@override
String get messageActionMultipleMarkUnseen => 'Mark as unread';
@override
String get messageActionMultipleMarkFlagged => 'Flag messages';
@override
String get messageActionMultipleMarkUnflagged => 'Unflag messages';
@override
String get messageActionViewInSafeMode => 'View without external content';
@override
String get emailSenderUnknown => '<no sender>';
@override
String get dateRangeFuture => 'future';
@override
String get dateRangeTomorrow => 'tomorrow';
@override
String get dateRangeToday => 'today';
@override
String get dateRangeYesterday => 'yesterday';
@override
String get dateRangeCurrentWeek => 'this week';
@override
String get dateRangeLastWeek => 'last week';
@override
String get dateRangeCurrentMonth => 'this month';
@override
String get dateRangeLastMonth => 'last month';
@override
String get dateRangeCurrentYear => 'this year';
@override
String get dateRangeLongAgo => 'long ago';
@override
String get dateUndefined => 'undefined';
@override
String get dateDayToday => 'today';
@override
String get dateDayYesterday => 'yesterday';
@override
String dateDayLastWeekday(String day) {
return 'last $day';
}
@override
String get drawerEntryAbout => 'About Maily';
@override
String get drawerEntrySettings => 'Settings';
@override
String drawerAccountsSectionTitle(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString accounts',
one: 'One account',
);
return '$_temp0';
}
@override
String get drawerEntryAddAccount => 'Add account';
@override
String get unifiedAccountName => 'Unified account';
@override
String get unifiedFolderInbox => 'Unified Inbox';
@override
String get unifiedFolderSent => 'Unified Sent';
@override
String get unifiedFolderDrafts => 'Unified Drafts';
@override
String get unifiedFolderTrash => 'Unified Trash';
@override
String get unifiedFolderArchive => 'Unified Archive';
@override
String get unifiedFolderJunk => 'Unified Junk';
@override
String get folderInbox => 'Inbox';
@override
String get folderSent => 'Sent';
@override
String get folderDrafts => 'Drafts';
@override
String get folderTrash => 'Trash';
@override
String get folderArchive => 'Archive';
@override
String get folderJunk => 'Junk';
@override
String get folderUnknown => 'Unknown';
@override
String get viewContentsAction => 'View contents';
@override
String get viewSourceAction => 'View source';
@override
String get detailsErrorDownloadInfo => 'Message could not be downloaded.';
@override
String get detailsErrorDownloadRetry => 'Retry';
@override
String get detailsHeaderFrom => 'From';
@override
String get detailsHeaderTo => 'To';
@override
String get detailsHeaderCc => 'CC';
@override
String get detailsHeaderBcc => 'BCC';
@override
String get detailsHeaderDate => 'Date';
@override
String get subjectUndefined => '<without subject>';
@override
String get detailsActionShowImages => 'Show images';
@override
String get detailsNewsletterActionUnsubscribe => 'Unsubscribe';
@override
String get detailsNewsletterActionResubscribe => 'Re-subscribe';
@override
String get detailsNewsletterStatusUnsubscribed => 'Unsubscribed';
@override
String get detailsNewsletterUnsubscribeDialogTitle => 'Unsubscribe';
@override
String detailsNewsletterUnsubscribeDialogQuestion(String listName) {
return 'Do you want to unsubscribe from the mailing list $listName?';
}
@override
String get detailsNewsletterUnsubscribeDialogAction => 'Unsubscribe';
@override
String get detailsNewsletterUnsubscribeSuccessTitle => 'Unsubscribed';
@override
String detailsNewsletterUnsubscribeSuccessMessage(String listName) {
return 'You are now unsubscribed from the mailing list $listName.';
}
@override
String get detailsNewsletterUnsubscribeFailureTitle => 'Not unsubscribed';
@override
String detailsNewsletterUnsubscribeFailureMessage(String listName) {
return 'Sorry, but I was unable to unsubscribe you from $listName automatically.';
}
@override
String get detailsNewsletterResubscribeDialogTitle => 'Re-subscribe';
@override
String detailsNewsletterResubscribeDialogQuestion(String listName) {
return 'Do you want to subscribe to this mailing list $listName again?';
}
@override
String get detailsNewsletterResubscribeDialogAction => 'Subscribe';
@override
String get detailsNewsletterResubscribeSuccessTitle => 'Subscribed';
@override
String detailsNewsletterResubscribeSuccessMessage(String listName) {
return 'You are now subscribed to the mailing list $listName again.';
}
@override
String get detailsNewsletterResubscribeFailureTitle => 'Not subscribed';
@override
String detailsNewsletterResubscribeFailureMessage(String listName) {
return 'Sorry, but the subscribe request has failed for mailing list $listName.';
}
@override
String get detailsSendReadReceiptAction => 'Send read receipt';
@override
String get detailsReadReceiptSentStatus => 'Read receipt sent ✔';
@override
String get detailsReadReceiptSubject => 'Read receipt';
@override
String get attachmentActionOpen => 'Open';
@override
String attachmentDecodeError(String details) {
return 'This attachment has an unsupported format or encoding.\nDetails: \$$details';
}
@override
String attachmentDownloadError(String details) {
return 'Unable to download this attachment.\nDetails: \$$details';
}
@override
String get messageActionReply => 'Reply';
@override
String get messageActionReplyAll => 'Reply all';
@override
String get messageActionForward => 'Forward';
@override
String get messageActionForwardAsAttachment => 'Forward as attachment';
@override
String messageActionForwardAttachments(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Forward $numberString attachments',
one: 'Forward attachment',
);
return '$_temp0';
}
@override
String get messagesActionForwardAttachments => 'Forward attachments';
@override
String get messageActionDelete => 'Delete';
@override
String get messageActionMoveToInbox => 'Move to inbox';
@override
String get messageActionMove => 'Move';
@override
String get messageStatusSeen => 'Is read';
@override
String get messageStatusUnseen => 'Is unread';
@override
String get messageStatusFlagged => 'Is flagged';
@override
String get messageStatusUnflagged => 'Is not flagged';
@override
String get messageActionMarkAsJunk => 'Mark as junk';
@override
String get messageActionMarkAsNotJunk => 'Mark as not junk';
@override
String get messageActionArchive => 'Archive';
@override
String get messageActionUnarchive => 'Move to Inbox';
@override
String get messageActionRedirect => 'Redirect';
@override
String get messageActionAddNotification => 'Add notification';
@override
String get resultDeleted => 'Deleted';
@override
String get resultMovedToJunk => 'Marked as junk';
@override
String get resultMovedToInbox => 'Moved to Inbox';
@override
String get resultArchived => 'Archived';
@override
String get resultRedirectedSuccess => 'Message redirected 👍';
@override
String resultRedirectedFailure(String details) {
return 'Unable to redirect message.\n\nThe server responded with the following details: \"$details\"';
}
@override
String get redirectTitle => 'Redirect';
@override
String get redirectInfo => 'Redirect this message to the following recipient(s). Redirecting does not alter the message.';
@override
String get redirectEmailInputRequired => 'You need to add at least one valid email address.';
@override
String searchQueryDescription(String folder) {
return 'Search in $folder...';
}
@override
String searchQueryTitle(String query) {
return 'Search \"$query\"';
}
@override
String get legaleseUsage => 'By using Maily you agree to our [PP] and to our [TC].';
@override
String get legalesePrivacyPolicy => 'Privacy Policy';
@override
String get legaleseTermsAndConditions => 'Terms & Conditions';
@override
String get aboutApplicationLegalese => 'Maily is free software published under the GNU General Public License.';
@override
String get feedbackActionSuggestFeature => 'Suggest a feature';
@override
String get feedbackActionReportProblem => 'Report a problem';
@override
String get feedbackActionHelpDeveloping => 'Help developing Maily';
@override
String get feedbackTitle => 'Feedback';
@override
String get feedbackIntro => 'Thank you for testing Maily!';
@override
String get feedbackProvideInfoRequest => 'Please provide this information when you report a problem:';
@override
String get feedbackResultInfoCopied => 'Copied to clipboard';
@override
String get accountsTitle => 'Accounts';
@override
String get accountsActionReorder => 'Reorder accounts';
@override
String get settingsTitle => 'Settings';
@override
String get settingsSecurityBlockExternalImages => 'Block external images';
@override
String get settingsSecurityBlockExternalImagesDescriptionTitle => 'External images';
@override
String get settingsSecurityBlockExternalImagesDescriptionText => 'Email messages can contain images that are either integrated or hosted on external servers. The latter, external images can expose information to the sender of the message, e.g. to let the sender know that you have opened the message. This option allows you to block such external images, which reduces the risk of exposing sensitive information. You can still opt in to load such images on a per-message-basis when you read a message.';
@override
String get settingsSecurityMessageRenderingHtml => 'Show full message contents';
@override
String get settingsSecurityMessageRenderingPlainText => 'Show only the text of messages';
@override
String get settingsSecurityLaunchModeLabel => 'How should Maily open links?';
@override
String get settingsSecurityLaunchModeExternal => 'Open links externally';
@override
String get settingsSecurityLaunchModeInApp => 'Open links in Maily';
@override
String get settingsActionAccounts => 'Manage accounts';
@override
String get settingsActionDesign => 'Appearance';
@override
String get settingsActionFeedback => 'Provide feedback';
@override
String get settingsActionWelcome => 'Show welcome';
@override
String get settingsReadReceipts => 'Read receipts';
@override
String get readReceiptsSettingsIntroduction => 'Do you want to display read receipt requests?';
@override
String get readReceiptOptionAlways => 'Always';
@override
String get readReceiptOptionNever => 'Never';
@override
String get settingsFolders => 'Folders';
@override
String get folderNamesIntroduction => 'What names do you prefer for your folders?';
@override
String get folderNamesSettingLocalized => 'Names given by Maily';
@override
String get folderNamesSettingServer => 'Names given by the service';
@override
String get folderNamesSettingCustom => 'My own custom names';
@override
String get folderNamesEditAction => 'Edit custom names';
@override
String get folderNamesCustomTitle => 'Custom names';
@override
String get folderAddAction => 'Create folder';
@override
String get folderAddTitle => 'Create folder';
@override
String get folderAddNameLabel => 'Name';
@override
String get folderAddNameHint => 'Name of the new folder';
@override
String get folderAccountLabel => 'Account';
@override
String get folderMailboxLabel => 'Folder';
@override
String get folderAddResultSuccess => 'Folder created 😊';
@override
String folderAddResultFailure(String details) {
return 'Folder could not be created.\n\nThe server responded with $details';
}
@override
String get folderDeleteAction => 'Delete';
@override
String get folderDeleteConfirmTitle => 'Confirm';
@override
String folderDeleteConfirmText(String name) {
return 'Do you really want to delete the folder $name?';
}
@override
String get folderDeleteResultSuccess => 'Folder deleted.';
@override
String folderDeleteResultFailure(String details) {
return 'Folder could not be deleted.\n\nThe server responded with $details';
}
@override
String get settingsDevelopment => 'Development settings';
@override
String get developerModeTitle => 'Development mode';
@override
String get developerModeIntroduction => 'If you enable the development mode you will be able to view the source code of messages and convert text attachments to messages.';
@override
String get developerModeEnable => 'Enable development mode';
@override
String get developerShowAsEmail => 'Convert text to email';
@override
String get developerShowAsEmailFailed => 'This text cannot be converted into a MIME message.';
@override
String get designTitle => 'Design Settings';
@override
String get designSectionThemeTitle => 'Theme';
@override
String get designThemeOptionLight => 'Light';
@override
String get designThemeOptionDark => 'Dark';
@override
String get designThemeOptionSystem => 'System';
@override
String get designThemeOptionCustom => 'Custom';
@override
String get designSectionCustomTitle => 'Enable dark theme';
@override
String designThemeCustomStart(String time) {
return 'from $time';
}
@override
String designThemeCustomEnd(String time) {
return 'until $time';
}
@override
String get designSectionColorTitle => 'Color Scheme';
@override
String get securitySettingsTitle => 'Security';
@override
String get securitySettingsIntro => 'Adapt the security settings to your personal needs.';
@override
String get securityUnlockWithFaceId => 'Unlock Maily with Face ID.';
@override
String get securityUnlockWithTouchId => 'Unlock Maily with Touch ID.';
@override
String get securityUnlockReason => 'Unlock Maily.';
@override
String get securityUnlockDisableReason => 'Unlock Maily to turn off lock.';
@override
String get securityUnlockNotAvailable => 'Your device does not support biometrics, possibly you need to set up unlock options first.';
@override
String get securityUnlockLabel => 'Lock Maily';
@override
String get securityUnlockDescriptionTitle => 'Lock Maily';
@override
String get securityUnlockDescriptionText => 'You can choose to lock access to Maily, so that others cannot read your email even when they have access to your device.';
@override
String get securityLockImmediately => 'Lock immediately';
@override
String get securityLockAfter5Minutes => 'Lock after 5 minutes';
@override
String get securityLockAfter30Minutes => 'Lock after 30 minutes';
@override
String get lockScreenTitle => 'Maily is locked';
@override
String get lockScreenIntro => 'Maily is locked, please authenticate to proceed.';
@override
String get lockScreenUnlockAction => 'Unlock';
@override
String get addAccountTitle => 'Add Account';
@override
String get addAccountEmailLabel => 'Email';
@override
String get addAccountEmailHint => 'Please enter your email address';
@override
String addAccountResolvingSettingsLabel(String email) {
return 'Resolving $email...';
}
@override
String addAccountResolvedSettingsWrongAction(String provider) {
return 'Not on $provider?';
}
@override
String addAccountResolvingSettingsFailedInfo(String email) {
return 'Unable to resolve $email. Please go back to change it or set up the account manually.';
}
@override
String get addAccountEditManuallyAction => 'Edit manually';
@override
String get addAccountPasswordLabel => 'Password';
@override
String get addAccountPasswordHint => 'Please enter your password';
@override
String get addAccountApplicationPasswordRequiredInfo => 'This provider requires you to set up an app specific password.';
@override
String get addAccountApplicationPasswordRequiredButton => 'Create app specific password';
@override
String get addAccountApplicationPasswordRequiredAcknowledged => 'I already have an app password';
@override
String get addAccountVerificationStep => 'Verification';
@override
String get addAccountSetupAccountStep => 'Account Setup';
@override
String addAccountVerifyingSettingsLabel(String email) {
return 'Verifying $email...';
}
@override
String addAccountVerifyingSuccessInfo(String email) {
return 'Successfully signed into $email.';
}
@override
String addAccountVerifyingFailedInfo(String email) {
return 'Sorry, but there was a problem. Please check your email $email and password.';
}
@override
String addAccountOauthOptionsText(String provider) {
return 'Sign in with $provider or create an app-specific password.';
}
@override
String addAccountOauthSignIn(String provider) {
return 'Sign in with $provider';
}
@override
String get addAccountOauthSignInGoogle => 'Sign in with Google';
@override
String get addAccountOauthSignInWithAppPassword => 'Alternatively, create an app password to sign in.';
@override
String get accountAddImapAccessSetupMightBeRequired => 'Your provider might require you to setup access for email apps manually.';
@override
String get addAccountSetupImapAccessButtonLabel => 'Setup email access';
@override
String get addAccountNameOfUserLabel => 'Your name';
@override
String get addAccountNameOfUserHint => 'The name that recipients see';
@override
String get addAccountNameOfAccountLabel => 'Account name';
@override
String get addAccountNameOfAccountHint => 'Please enter the name of your account';
@override
String editAccountTitle(String name) {
return 'Edit $name';
}
@override
String editAccountFailureToConnectInfo(String name) {
return 'Maily could not connect $name.';
}
@override
String get editAccountFailureToConnectRetryAction => 'Retry';
@override
String get editAccountFailureToConnectChangePasswordAction => 'Change Password';
@override
String get editAccountFailureToConnectFixedTitle => 'Connected';
@override
String get editAccountFailureToConnectFixedInfo => 'The account is connected again.';
@override
String get editAccountIncludeInUnifiedLabel => 'Include in unified account';
@override
String editAccountAliasLabel(String email) {
return 'Alias email addresses for $email:';
}
@override
String get editAccountNoAliasesInfo => 'You have no known aliases for this account yet.';
@override
String editAccountAliasRemoved(String email) {
return '$email alias removed';
}
@override
String get editAccountAddAliasAction => 'Add alias';
@override
String get editAccountPlusAliasesSupported => 'Supports + aliases';
@override
String get editAccountCheckPlusAliasAction => 'Test support for + aliases';
@override
String get editAccountBccMyself => 'BCC myself';
@override
String get editAccountBccMyselfDescriptionTitle => 'BCC myself';
@override
String get editAccountBccMyselfDescriptionText => 'You can automatically send messages to yourself for every message you send from this account with the \"BCC myself\" feature. Usually this is not required and wanted as all outgoing messages are stored in the \"Sent\" folder anyhow.';
@override
String get editAccountServerSettingsAction => 'Edit server settings';
@override
String get editAccountDeleteAccountAction => 'Delete account';
@override
String get editAccountDeleteAccountConfirmationTitle => 'Confirm';
@override
String editAccountDeleteAccountConfirmationQuery(String name) {
return 'Do you want to delete the account $name?';
}
@override
String editAccountTestPlusAliasTitle(String name) {
return '+ Aliases for $name';
}
@override
String get editAccountTestPlusAliasStepIntroductionTitle => 'Introduction';
@override
String editAccountTestPlusAliasStepIntroductionText(String accountName, String example) {
return 'Your account $accountName might support so called + aliases like $example.\nA + alias helps you to protect your identity and helps you against spam.\nTo test this, a test message will be sent to this generated address. If it arrives, your provider supports + aliases and you can easily generate them on demand when writing a new mail message.';
}
@override
String get editAccountTestPlusAliasStepTestingTitle => 'Testing';
@override
String get editAccountTestPlusAliasStepResultTitle => 'Result';
@override
String editAccountTestPlusAliasStepResultSuccess(String name) {
return 'Your account $name supports + aliases.';
}
@override
String editAccountTestPlusAliasStepResultNoSuccess(String name) {
return 'Your account $name does not support + aliases.';
}
@override
String get editAccountAddAliasTitle => 'Add alias';
@override
String get editAccountEditAliasTitle => 'Edit alias';
@override
String get editAccountAliasAddAction => 'Add';
@override
String get editAccountAliasUpdateAction => 'Update';
@override
String get editAccountEditAliasNameLabel => 'Alias name';
@override
String get editAccountEditAliasEmailLabel => 'Alias email';
@override
String get editAccountEditAliasEmailHint => 'Your alias email address';
@override
String editAccountEditAliasDuplicateError(String email) {
return 'There is already an alias with $email.';
}
@override
String get editAccountEnableLogging => 'Enable logging';
@override
String get editAccountLoggingEnabled => 'Log enabled, please restart';
@override
String get editAccountLoggingDisabled => 'Log disabled, please restart';
@override
String get accountDetailsFallbackTitle => 'Server Settings';
@override
String get errorTitle => 'Error';
@override
String get accountProviderStepTitle => 'Email Service Provider';
@override
String get accountProviderCustom => 'Other email service';
@override
String accountDetailsErrorHostProblem(String incomingHost, String outgoingHost) {
return 'Maily cannot reach the specified mail server. Please check your incoming server setting \"$incomingHost\" and your outgoing server setting \"$outgoingHost\".';
}
@override
String accountDetailsErrorLoginProblem(String userName, String password) {
return 'Unable to log your in. Please check your user name \"$userName\" and your password \"$password\".';
}
@override
String get accountDetailsUserNameLabel => 'Login name';
@override
String get accountDetailsUserNameHint => 'Your user name, if different from email';
@override
String get accountDetailsPasswordLabel => 'Login password';
@override
String get accountDetailsPasswordHint => 'Your password';
@override
String get accountDetailsBaseSectionTitle => 'Base settings';
@override
String get accountDetailsIncomingLabel => 'Incoming server';
@override
String get accountDetailsIncomingHint => 'Domain like imap.domain.com';
@override
String get accountDetailsOutgoingLabel => 'Outgoing server';
@override
String get accountDetailsOutgoingHint => 'Domain like smtp.domain.com';
@override
String get accountDetailsAdvancedIncomingSectionTitle => 'Advanced incoming settings';
@override
String get accountDetailsIncomingServerTypeLabel => 'Incoming type:';
@override
String get accountDetailsOptionAutomatic => 'automatic';
@override
String get accountDetailsIncomingSecurityLabel => 'Incoming security:';
@override
String get accountDetailsSecurityOptionNone => 'Plain (no encryption)';
@override
String get accountDetailsIncomingPortLabel => 'Incoming port';
@override
String get accountDetailsPortHint => 'Leave empty to determine automatically';
@override
String get accountDetailsIncomingUserNameLabel => 'Incoming user name';
@override
String get accountDetailsAlternativeUserNameHint => 'Your user name, if different from above';
@override
String get accountDetailsIncomingPasswordLabel => 'Incoming password';
@override
String get accountDetailsAlternativePasswordHint => 'Your password, if different from above';
@override
String get accountDetailsAdvancedOutgoingSectionTitle => 'Advanced outgoing settings';
@override
String get accountDetailsOutgoingServerTypeLabel => 'Outgoing type:';
@override
String get accountDetailsOutgoingSecurityLabel => 'Outgoing security:';
@override
String get accountDetailsOutgoingPortLabel => 'Outgoing port';
@override
String get accountDetailsOutgoingUserNameLabel => 'Outgoing user name';
@override
String get accountDetailsOutgoingPasswordLabel => 'Outgoing password';
@override
String get composeTitleNew => 'New message';
@override
String get composeTitleForward => 'Forward';
@override
String get composeTitleReply => 'Reply';
@override
String get composeEmptyMessage => 'empty message';
@override
String get composeWarningNoSubject => 'You have not specified a subject. Do you want to sent the message without a subject?';
@override
String get composeActionSentWithoutSubject => 'Send';
@override
String get composeMailSendSuccess => 'Mail sent 😊';
@override
String composeSendErrorInfo(String details) {
return 'Sorry, your mail could not be send. We received the following error:\n$details.';
}
@override
String get composeRequestReadReceiptAction => 'Request read receipt';
@override
String get composeSaveDraftAction => 'Save as draft';
@override
String get composeMessageSavedAsDraft => 'Draft saved';
@override
String composeMessageSavedAsDraftErrorInfo(String details) {
return 'Your draft could not be saved with the following error:\n$details';
}
@override
String get composeConvertToPlainTextEditorAction => 'Convert to plain text';
@override
String get composeConvertToHtmlEditorAction => 'Convert to rich message (HTML)';
@override
String get composeContinueEditingAction => 'Continue editing';
@override
String get composeCreatePlusAliasAction => 'Create new + alias...';
@override
String get composeSenderHint => 'Sender';
@override
String get composeRecipientHint => 'Recipient email';
@override
String get composeSubjectLabel => 'Subject';
@override
String get composeSubjectHint => 'Message subject';
@override
String get composeAddAttachmentAction => 'Add';
@override
String composeRemoveAttachmentAction(String name) {
return 'Remove $name';
}
@override
String get composeLeftByMistake => 'Left by mistake?';
@override
String get attachTypeFile => 'File';
@override
String get attachTypePhoto => 'Photo';
@override
String get attachTypeVideo => 'Video';
@override
String get attachTypeAudio => 'Audio';
@override
String get attachTypeLocation => 'Location';
@override
String get attachTypeGif => 'Animated Gif';
@override
String get attachTypeGifSearch => 'search GIPHY';
@override
String get attachTypeSticker => 'Sticker';
@override
String get attachTypeStickerSearch => 'search GIPHY';
@override
String get attachTypeAppointment => 'Appointment';
@override
String get languageSettingTitle => 'Language';
@override
String get languageSettingLabel => 'Choose the language for Maily:';
@override
String get languageSettingSystemOption => 'System language';
@override
String get languageSettingConfirmationTitle => 'Use English for Maily?';
@override
String get languageSettingConfirmationQuery => 'Please confirm to use English as your chosen language.';
@override
String get languageSetInfo => 'Maily is now shown in English.';
@override
String get languageSystemSetInfo => 'Maily will now use the system\'s language or English if the system\'s language is not supported.';
@override
String get swipeSettingTitle => 'Swipe gestures';
@override
String get swipeSettingLeftToRightLabel => 'Left to right swipe';
@override
String get swipeSettingRightToLeftLabel => 'Right to left swipe';
@override
String get swipeSettingChangeAction => 'Change';
@override
String get signatureSettingsTitle => 'Signature';
@override
String get signatureSettingsComposeActionsInfo => 'Enable the signature for the following messages:';
@override
String get signatureSettingsAccountInfo => 'You can specify account specific signatures in the account settings.';
@override
String signatureSettingsAddForAccount(String account) {
return 'Add signature for $account';
}
@override
String get defaultSenderSettingsTitle => 'Default sender';
@override
String get defaultSenderSettingsLabel => 'Select the sender for new messages.';
@override
String defaultSenderSettingsFirstAccount(String email) {
return 'First account ($email)';
}
@override
String get defaultSenderSettingsAliasInfo => 'You can set up email alias addresses in the [AS].';
@override
String get defaultSenderSettingsAliasAccountSettings => 'account settings';
@override
String get replySettingsTitle => 'Message format';
@override
String get replySettingsIntro => 'In what format do you want to answer or forward email by default?';
@override
String get replySettingsFormatHtml => 'Always rich format (HTML)';
@override
String get replySettingsFormatSameAsOriginal => 'Use same format as originating email';
@override
String get replySettingsFormatPlainText => 'Always text-only';
@override
String get moveTitle => 'Move message';
@override
String moveSuccess(String mailbox) {
return 'Messaged moved to $mailbox.';
}
@override
String get editorArtInputLabel => 'Your input';
@override
String get editorArtInputHint => 'Enter text here';
@override
String get editorArtWaitingForInputHint => 'waiting for input...';
@override
String get fontSerifBold => 'Serif bold';
@override
String get fontSerifItalic => 'Serif italic';
@override
String get fontSerifBoldItalic => 'Serif bold italic';
@override
String get fontSans => 'Sans';
@override
String get fontSansBold => 'Sans bold';
@override
String get fontSansItalic => 'Sans italic';
@override
String get fontSansBoldItalic => 'Sans bold italic';
@override
String get fontScript => 'Script';
@override
String get fontScriptBold => 'Script bold';
@override
String get fontFraktur => 'Fraktur';
@override
String get fontFrakturBold => 'Fraktur bold';
@override
String get fontMonospace => 'Monospace';
@override
String get fontFullwidth => 'Fullwidth';
@override
String get fontDoublestruck => 'Double struck';
@override
String get fontCapitalized => 'Capitalized';
@override
String get fontCircled => 'Circled';
@override
String get fontParenthesized => 'Parenthesized';
@override
String get fontUnderlinedSingle => 'Underlined';
@override
String get fontUnderlinedDouble => 'Underlined double';
@override
String get fontStrikethroughSingle => 'Strike through';
@override
String get fontCrosshatch => 'Crosshatch';
@override
String accountLoadError(String name) {
return 'Unable to connect to your account $name. Has the password been changed?';
}
@override
String get accountLoadErrorEditAction => 'Edit account';
@override
String get extensionsTitle => 'Extensions';
@override
String get extensionsIntro => 'With extensions e-mail service providers, companies and developers can adapt Maily with useful functionalities.';
@override
String get extensionsLearnMoreAction => 'Learn more about extensions';
@override
String get extensionsReloadAction => 'Reload extensions';
@override
String get extensionDeactivateAllAction => 'Deactivate all extensions';
@override
String get extensionsManualAction => 'Load manually';
@override
String get extensionsManualUrlLabel => 'Url of extension';
@override
String extensionsManualLoadingError(String url) {
return 'Unable to download extension from \"$url\".';
}
@override
String get icalendarAcceptTentatively => 'Tentatively';
@override
String get icalendarActionChangeParticipantStatus => 'Change';
@override
String get icalendarLabelSummary => 'Title';
@override
String get icalendarNoSummaryInfo => '(no title)';
@override
String get icalendarLabelDescription => 'Description';
@override
String get icalendarLabelStart => 'Start';
@override
String get icalendarLabelEnd => 'End';
@override
String get icalendarLabelDuration => 'Duration';
@override
String get icalendarLabelLocation => 'Location';
@override
String get icalendarLabelTeamsUrl => 'Link';
@override
String get icalendarLabelRecurrenceRule => 'Repeats';
@override
String get icalendarLabelParticipants => 'Participants';
@override
String get icalendarParticipantStatusNeedsAction => 'You are asked to answer this invitation.';
@override
String get icalendarParticipantStatusAccepted => 'You have accepted this invitation.';
@override
String get icalendarParticipantStatusDeclined => 'You have declined this invitation.';
@override
String get icalendarParticipantStatusAcceptedTentatively => 'You have tentatively accepted this invitation.';
@override
String get icalendarParticipantStatusDelegated => 'You have delegated this invitation.';
@override
String get icalendarParticipantStatusInProcess => 'The task is in progress.';
@override
String get icalendarParticipantStatusPartial => 'The task is partially done.';
@override
String get icalendarParticipantStatusCompleted => 'The task is done.';
@override
String get icalendarParticipantStatusOther => 'Your status is unknown.';
@override
String get icalendarParticipantStatusChangeTitle => 'Your Status';
@override
String get icalendarParticipantStatusChangeText => 'Do you want to accept this invitation?';
@override
String icalendarParticipantStatusSentFailure(String details) {
return 'Unable to send reply.\nThe server responded with the following details:\n$details';
}
@override
String get icalendarExportAction => 'Export';
@override
String icalendarReplyStatusNeedsAction(String attendee) {
return '$attendee has not answered this invitation.';
}
@override
String icalendarReplyStatusAccepted(String attendee) {
return '$attendee has accepted the appointment.';
}
@override
String icalendarReplyStatusDeclined(String attendee) {
return '$attendee has declined this invitation.';
}
@override
String icalendarReplyStatusAcceptedTentatively(String attendee) {
return '$attendee has tentatively accepted this invitation.';
}
@override
String icalendarReplyStatusDelegated(String attendee) {
return '$attendee has delegated this invitation.';
}
@override
String icalendarReplyStatusInProcess(String attendee) {
return '$attendee has started this task.';
}
@override
String icalendarReplyStatusPartial(String attendee) {
return '$attendee has partially done this task.';
}
@override
String icalendarReplyStatusCompleted(String attendee) {
return '$attendee has finished this task.';
}
@override
String icalendarReplyStatusOther(String attendee) {
return '$attendee has answered with an unknown status.';
}
@override
String get icalendarReplyWithoutParticipants => 'This calendar reply contains no participants.';
@override
String icalendarReplyWithoutStatus(String attendee) {
return '$attendee replied without an participation status.';
}
@override
String get composeAppointmentTitle => 'Create Appointment';
@override
String get composeAppointmentLabelDay => 'day';
@override
String get composeAppointmentLabelTime => 'time';
@override
String get composeAppointmentLabelAllDayEvent => 'All day';
@override
String get composeAppointmentLabelRepeat => 'Repeat';
@override
String get composeAppointmentLabelRepeatOptionNever => 'Never';
@override
String get composeAppointmentLabelRepeatOptionDaily => 'Daily';
@override
String get composeAppointmentLabelRepeatOptionWeekly => 'Weekly';
@override
String get composeAppointmentLabelRepeatOptionMonthly => 'Monthly';
@override
String get composeAppointmentLabelRepeatOptionYearly => 'Annually';
@override
String get composeAppointmentRecurrenceFrequencyLabel => 'Frequency';
@override
String get composeAppointmentRecurrenceIntervalLabel => 'Interval';
@override
String get composeAppointmentRecurrenceDaysLabel => 'On days';
@override
String get composeAppointmentRecurrenceUntilLabel => 'Until';
@override
String get composeAppointmentRecurrenceUntilOptionUnlimited => 'Unlimited';
@override
String composeAppointmentRecurrenceUntilOptionRecommended(String duration) {
return 'Recommended ($duration)';
}
@override
String get composeAppointmentRecurrenceUntilOptionSpecificDate => 'Until chosen date';
@override
String composeAppointmentRecurrenceMonthlyOnDayOfMonth(int day) {
final intl.NumberFormat dayNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String dayString = dayNumberFormat.format(day);
return 'On the $dayString. day of the month';
}
@override
String get composeAppointmentRecurrenceMonthlyOnWeekDay => 'Weekday in month';
@override
String get composeAppointmentRecurrenceFirst => 'First';
@override
String get composeAppointmentRecurrenceSecond => 'Second';
@override
String get composeAppointmentRecurrenceThird => 'Third';
@override
String get composeAppointmentRecurrenceLast => 'Last';
@override
String get composeAppointmentRecurrenceSecondLast => 'Second-last';
@override
String durationYears(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString years',
one: '1 year',
);
return '$_temp0';
}
@override
String durationMonths(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString months',
one: '1 month',
);
return '$_temp0';
}
@override
String durationWeeks(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString weeks',
one: '1 week',
);
return '$_temp0';
}
@override
String durationDays(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString days',
one: '1 day',
);
return '$_temp0';
}
@override
String durationHours(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString hours',
one: '1 hour',
);
return '$_temp0';
}
@override
String durationMinutes(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString minutes',
one: '1 minute',
);
return '$_temp0';
}
@override
String get durationEmpty => 'No duration';
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/localization/provider.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'provider.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
String _$currentAppLocalizationHash() =>
r'c18983e4ccf75e45ed6f0a56e73423a2c1e5fa10';
/// See also [CurrentAppLocalization].
@ProviderFor(CurrentAppLocalization)
final currentAppLocalizationProvider =
NotifierProvider<CurrentAppLocalization, AppLocalizations>.internal(
CurrentAppLocalization.new,
name: r'currentAppLocalizationProvider',
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
? null
: _$currentAppLocalizationHash,
dependencies: null,
allTransitiveDependencies: null,
);
typedef _$CurrentAppLocalization = Notifier<AppLocalizations>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/localization/app_localizations_de.g.dart
|
import 'package:intl/intl.dart' as intl;
import 'app_localizations.g.dart';
/// The translations for German (`de`).
class AppLocalizationsDe extends AppLocalizations {
AppLocalizationsDe([String locale = 'de']) : super(locale);
@override
String get signature => 'Mit Maily gesendet';
@override
String get actionCancel => 'Abbrechen';
@override
String get actionOk => 'OK';
@override
String get actionDone => 'Fertig';
@override
String get actionNext => 'Weiter';
@override
String get actionSkip => 'Überspringen';
@override
String get actionUndo => 'Rückgängig';
@override
String get actionDelete => 'Löschen';
@override
String get actionAccept => 'Akzeptieren';
@override
String get actionDecline => 'Ablehnen';
@override
String get actionEdit => 'Bearbeiten';
@override
String get actionAddressCopy => 'Kopieren';
@override
String get actionAddressCompose => 'Neue Nachricht';
@override
String get actionAddressSearch => 'Suchen';
@override
String get splashLoading1 => 'Maily startet...';
@override
String get splashLoading2 => 'Maily fängt an zu arbeiten...';
@override
String get splashLoading3 => 'Maily startet in 10, 9, 8...';
@override
String get welcomePanel1Title => 'Maily';
@override
String get welcomePanel1Text => 'Willkommen zu Maily, deinem freundlichen und schnellen E-Mail Helferlein!';
@override
String get welcomePanel2Title => 'Konten';
@override
String get welcomePanel2Text => 'Verwalte beliebig viele E-Mail Konten. Lese und suche Mails in allen Konten gleichzeitig';
@override
String get welcomePanel3Title => 'Wisch und drück mich!';
@override
String get welcomePanel3Text => 'Wische eine E-Mail um sie zu löschen oder als gelesen zu markieren. Halte eine E-Mail lange um mehrere gleichzeitig zu bearbeiten.';
@override
String get welcomePanel4Title => 'Halte Deinen Posteingang sauber';
@override
String get welcomePanel4Text => 'Melde Dich von Newslettern mit einem Klick ab.';
@override
String get welcomeActionSignIn => 'Melde dich bei deinem E-Mail Konto an';
@override
String get homeSearchHint => 'Deine Suche';
@override
String get homeActionsShowAsStack => 'Stapel Modus';
@override
String get homeActionsShowAsList => 'Listen Modus';
@override
String get homeEmptyFolderMessage => 'Alles fertig!\n\nEs gibt keine E-Mails in diesem Ordner.';
@override
String get homeEmptySearchMessage => 'Keine E-Mails gefunden.';
@override
String get homeDeleteAllTitle => 'Bestätigung';
@override
String get homeDeleteAllQuestion => 'Wirklich alle E-Mails löschen?';
@override
String get homeDeleteAllAction => 'Alle löschen';
@override
String get homeDeleteAllScrubOption => 'Endgültig löschen';
@override
String get homeDeleteAllSuccess => 'Alle E-Mails gelöscht.';
@override
String get homeMarkAllSeenAction => 'Gelesen';
@override
String get homeMarkAllUnseenAction => 'Ungelesen';
@override
String get homeFabTooltip => 'Neue E-Mail';
@override
String get homeLoadingMessageSourceTitle => 'Lade Daten...';
@override
String homeLoading(String name) {
return 'Lade $name...';
}
@override
String get swipeActionToggleRead => 'Gelesen / ungelesen';
@override
String get swipeActionDelete => 'Löschen';
@override
String get swipeActionMarkJunk => 'Als Spam markieren';
@override
String get swipeActionArchive => 'Archivieren';
@override
String get swipeActionFlag => 'Markieren';
@override
String multipleMovedToJunk(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Nachrichten als Spam markiert',
one: 'Eine Nachricht als Spam markiert',
);
return '$_temp0';
}
@override
String multipleMovedToInbox(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Nachrichten in Inbox geschoben',
one: 'Eine Nachricht in Inbox geschoben',
);
return '$_temp0';
}
@override
String multipleMovedToArchive(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Nachrichten archiviert',
one: 'Eine Nachricht archiviert',
);
return '$_temp0';
}
@override
String multipleMovedToTrash(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Nachrichten gelöscht',
one: 'Eine Nachricht gelöscht',
);
return '$_temp0';
}
@override
String get multipleSelectionNeededInfo => 'Wähle mindestens eine Nachricht aus.';
@override
String multipleSelectionActionFailed(String details) {
return 'Unable to perform action\nDetails: $details';
}
@override
String multipleMoveTitle(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Nachrichten verschieben',
one: 'Nachricht verschieben',
);
return '$_temp0';
}
@override
String get messageActionMultipleMarkSeen => 'Als gelesen markieren';
@override
String get messageActionMultipleMarkUnseen => 'Als ungelesen markieren';
@override
String get messageActionMultipleMarkFlagged => 'Markieren';
@override
String get messageActionMultipleMarkUnflagged => 'Markierung entfernen';
@override
String get messageActionViewInSafeMode => 'Ohne externe Inhalte anzeigen';
@override
String get emailSenderUnknown => '<unbekannt>';
@override
String get dateRangeFuture => 'Zukunft';
@override
String get dateRangeTomorrow => 'morgen';
@override
String get dateRangeToday => 'heute';
@override
String get dateRangeYesterday => 'gestern';
@override
String get dateRangeCurrentWeek => 'diese Woche';
@override
String get dateRangeLastWeek => 'letzte Woche';
@override
String get dateRangeCurrentMonth => 'diesen Monat';
@override
String get dateRangeLastMonth => 'letzten Monat';
@override
String get dateRangeCurrentYear => 'dieses Jahr';
@override
String get dateRangeLongAgo => 'lange her';
@override
String get dateUndefined => 'undefiniert';
@override
String get dateDayToday => 'heute';
@override
String get dateDayYesterday => 'gestern';
@override
String dateDayLastWeekday(String day) {
return 'letzten $day';
}
@override
String get drawerEntryAbout => 'Über Maily';
@override
String get drawerEntrySettings => 'Einstellungen';
@override
String drawerAccountsSectionTitle(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Konten',
one: '1 Konto',
);
return '$_temp0';
}
@override
String get drawerEntryAddAccount => 'Konto hinzufügen';
@override
String get unifiedAccountName => 'Alle Konten';
@override
String get unifiedFolderInbox => 'Alle Posteingänge';
@override
String get unifiedFolderSent => 'Alle Gesendeten';
@override
String get unifiedFolderDrafts => 'Alle Entwürfe';
@override
String get unifiedFolderTrash => 'Alle Gelöschten';
@override
String get unifiedFolderArchive => 'Alle Archivierten';
@override
String get unifiedFolderJunk => 'Alle Spam Nachrichten';
@override
String get folderInbox => 'Posteingang';
@override
String get folderSent => 'Gesendete Nachrichten';
@override
String get folderDrafts => 'Entwürfe';
@override
String get folderTrash => 'Papierkorb';
@override
String get folderArchive => 'Archiv';
@override
String get folderJunk => 'Spam Nachrichten';
@override
String get folderUnknown => 'Unbekannt';
@override
String get viewContentsAction => 'Inhalt anzeigen';
@override
String get viewSourceAction => 'Sourcecode anzeigen';
@override
String get detailsErrorDownloadInfo => 'E-Mail konnte nicht geladen werden.';
@override
String get detailsErrorDownloadRetry => 'wiederholen';
@override
String get detailsHeaderFrom => 'Von';
@override
String get detailsHeaderTo => 'An';
@override
String get detailsHeaderCc => 'CC';
@override
String get detailsHeaderBcc => 'BCC';
@override
String get detailsHeaderDate => 'Datum';
@override
String get subjectUndefined => '<ohne Betreff>';
@override
String get detailsActionShowImages => 'Bilder anzeigen';
@override
String get detailsNewsletterActionUnsubscribe => 'Abbestellen';
@override
String get detailsNewsletterActionResubscribe => 'Neu abbonieren';
@override
String get detailsNewsletterStatusUnsubscribed => 'Abbestellt';
@override
String get detailsNewsletterUnsubscribeDialogTitle => 'Abbestellen';
@override
String detailsNewsletterUnsubscribeDialogQuestion(String listName) {
return 'Möchtest du die Mailingliste $listName abbestellen?';
}
@override
String get detailsNewsletterUnsubscribeDialogAction => 'Abbestellen';
@override
String get detailsNewsletterUnsubscribeSuccessTitle => 'Abbestellt';
@override
String detailsNewsletterUnsubscribeSuccessMessage(String listName) {
return 'Du hast dich von der Mailingliste $listName erfolgreich abgemeldet.';
}
@override
String get detailsNewsletterUnsubscribeFailureTitle => 'Nicht abbestellt';
@override
String detailsNewsletterUnsubscribeFailureMessage(String listName) {
return 'Entschuldige, ich konnte dich nicht automatisch von $listName abmelden.';
}
@override
String get detailsNewsletterResubscribeDialogTitle => 'Abonnieren';
@override
String detailsNewsletterResubscribeDialogQuestion(String listName) {
return 'Möchtest du die Mailingliste $listName wieder abonnieren?';
}
@override
String get detailsNewsletterResubscribeDialogAction => 'Abonnieren';
@override
String get detailsNewsletterResubscribeSuccessTitle => 'Aboniert';
@override
String detailsNewsletterResubscribeSuccessMessage(String listName) {
return 'Du hast wieder die Mailingliste $listName abonniert.';
}
@override
String get detailsNewsletterResubscribeFailureTitle => 'Nicht abonniert';
@override
String detailsNewsletterResubscribeFailureMessage(String listName) {
return 'Entschuldige, ich konnte dich leider nicht automatisch bei der Mailingliste $listName anmelden.';
}
@override
String get detailsSendReadReceiptAction => 'Lesebestätigung senden';
@override
String get detailsReadReceiptSentStatus => 'Lesebestätigung gesendet ✔';
@override
String get detailsReadReceiptSubject => 'Lesebestätigung';
@override
String get attachmentActionOpen => 'Öffnen';
@override
String attachmentDecodeError(String details) {
return 'Dieses Attachment ist in einem unbekannten Format.\nDetails: \$$details';
}
@override
String attachmentDownloadError(String details) {
return 'Dieses Attachment konnte nicht heruntergeladen werden.\nDetails: \$$details';
}
@override
String get messageActionReply => 'Antworten';
@override
String get messageActionReplyAll => 'Allen antworten';
@override
String get messageActionForward => 'Weiterleiten';
@override
String get messageActionForwardAsAttachment => 'Als Anhang weiterleiten';
@override
String messageActionForwardAttachments(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Anhänge weiterleiten',
one: 'Anhang weiterleiten',
);
return '$_temp0';
}
@override
String get messagesActionForwardAttachments => 'Anhänge weiterleiten';
@override
String get messageActionDelete => 'Löschen';
@override
String get messageActionMoveToInbox => 'In Posteingang verschieben';
@override
String get messageActionMove => 'Verschieben';
@override
String get messageStatusSeen => 'Ist gelesen';
@override
String get messageStatusUnseen => 'Ist ungelesen';
@override
String get messageStatusFlagged => 'Ist markiert';
@override
String get messageStatusUnflagged => 'Ist nicht markiert';
@override
String get messageActionMarkAsJunk => 'Als Spam markieren';
@override
String get messageActionMarkAsNotJunk => 'Als nicht-Spam markieren';
@override
String get messageActionArchive => 'Archivieren';
@override
String get messageActionUnarchive => 'In Posteingang verschieben';
@override
String get messageActionRedirect => 'Umleiten';
@override
String get messageActionAddNotification => 'Benachrichtigung hinzufügen';
@override
String get resultDeleted => 'Gelöscht';
@override
String get resultMovedToJunk => 'Als Spam markiert';
@override
String get resultMovedToInbox => 'In Posteingang verschoben';
@override
String get resultArchived => 'Archiviert';
@override
String get resultRedirectedSuccess => 'Nachricht umgeleitet 👍';
@override
String resultRedirectedFailure(String details) {
return 'Nachricht konnte nicht umgeleitet werden.\n\nDer Server meldet folgende Details: \"$details\"';
}
@override
String get redirectTitle => 'Umleiten';
@override
String get redirectInfo => 'Leite diese Nachricht an folgende Empfänger:innen um. Umleiten verändert nicht die Nachricht.';
@override
String get redirectEmailInputRequired => 'Bitte gebe mindestens eine gültige E-Mail-Adresse ein.';
@override
String searchQueryDescription(String folder) {
return 'Suche in $folder...';
}
@override
String searchQueryTitle(String query) {
return 'Suche \"$query\"';
}
@override
String get legaleseUsage => 'Durch die Nutzung von Maily stimmst du unserer [PP] und unseren [TC] zu.';
@override
String get legalesePrivacyPolicy => 'Datenschutzerlärung';
@override
String get legaleseTermsAndConditions => 'Bedingungen';
@override
String get aboutApplicationLegalese => 'Maily ist freie Software, die unter der GPL GNU General Public License veröffentlicht ist.';
@override
String get feedbackActionSuggestFeature => 'Feature vorschlagen';
@override
String get feedbackActionReportProblem => 'Problem berichten';
@override
String get feedbackActionHelpDeveloping => 'Hilf Maily zu entwickeln';
@override
String get feedbackTitle => 'Feedback';
@override
String get feedbackIntro => 'Danke, dass du Maily testest!';
@override
String get feedbackProvideInfoRequest => 'Bitte teile folgende Information mit, wenn du ein Problem berichtest:';
@override
String get feedbackResultInfoCopied => 'kopiert';
@override
String get accountsTitle => 'Konten';
@override
String get accountsActionReorder => 'Konten Reihenfolge ändern';
@override
String get settingsTitle => 'Einstellungen';
@override
String get settingsSecurityBlockExternalImages => 'Externe Bilder blockieren';
@override
String get settingsSecurityBlockExternalImagesDescriptionTitle => 'Externe Bilder';
@override
String get settingsSecurityBlockExternalImagesDescriptionText => 'E-Mail-Nachrichten können Bilder enthalten, die entweder auf externen Servern integriert oder gehostet werden. Die letzteren externen Bilder können dem Absender der Nachricht Informationen offen legen, z.B. um dem Absender mitzuteilen, dass Sie die Nachricht geöffnet haben. Mit dieser Option können Sie solche externen Bilder blockieren, was das Risiko verringert, sensible Informationen zu enthüllen. Wenn Sie eine Nachricht lesen, können Sie diese Bilder immer noch pro Nachricht laden.';
@override
String get settingsSecurityMessageRenderingHtml => 'Gesamte Nachricht anzeigen';
@override
String get settingsSecurityMessageRenderingPlainText => 'Nur den Text der Nachricht anzeigen';
@override
String get settingsSecurityLaunchModeLabel => 'Wie soll Maily Links öffnen?';
@override
String get settingsSecurityLaunchModeExternal => 'Öffne Links extern';
@override
String get settingsSecurityLaunchModeInApp => 'Öffne Links in Maily';
@override
String get settingsActionAccounts => 'Konten verwalten';
@override
String get settingsActionDesign => 'Darstellung';
@override
String get settingsActionFeedback => 'Feedback geben';
@override
String get settingsActionWelcome => 'Willkommen anzeigen';
@override
String get settingsReadReceipts => 'Lesebestätigungen';
@override
String get readReceiptsSettingsIntroduction => 'Sollen Lesebestätigungs-Anforderungen angezeigt werden?';
@override
String get readReceiptOptionAlways => 'Immer';
@override
String get readReceiptOptionNever => 'Nie';
@override
String get settingsFolders => 'Ordner';
@override
String get folderNamesIntroduction => 'Welche Ordner-Namen möchtest du nutzen?';
@override
String get folderNamesSettingLocalized => 'Von Maily vorgegebene Namen';
@override
String get folderNamesSettingServer => 'Vom Maildienst gegebene Namen';
@override
String get folderNamesSettingCustom => 'Meine eigenen Namen';
@override
String get folderNamesEditAction => 'Eigene Ordner Namen ändern';
@override
String get folderNamesCustomTitle => 'Eigene Namen';
@override
String get folderAddAction => 'Ordner erstellen';
@override
String get folderAddTitle => 'Ordner erstellen';
@override
String get folderAddNameLabel => 'Name';
@override
String get folderAddNameHint => 'Name des Ordners';
@override
String get folderAccountLabel => 'Konto';
@override
String get folderMailboxLabel => 'Erstelle in';
@override
String get folderAddResultSuccess => 'Ordner erstellt 😊';
@override
String folderAddResultFailure(String details) {
return 'Der Ordner konnte nicht erstellt werden.\n\nDer Server antwortete mit \"$details\".';
}
@override
String get folderDeleteAction => 'Löschen';
@override
String get folderDeleteConfirmTitle => 'Bestätigen';
@override
String folderDeleteConfirmText(String name) {
return 'Möchtest Du den Ordner $name wirklich löschen?';
}
@override
String get folderDeleteResultSuccess => 'Ordner gelöscht.';
@override
String folderDeleteResultFailure(String details) {
return 'Der Ordner konnte nicht gelöscht werden.\n\nDer Server antwortete mit \"$details\".';
}
@override
String get settingsDevelopment => 'Entwicklungs-Einstellungen';
@override
String get developerModeTitle => 'Entwicklungs-Modus';
@override
String get developerModeIntroduction => 'Mit einem aktivierten Entwicklungs-Modus kannst du den Sourcecode von Mails einsehen, siehst alle Fehler-Details und Text Anhänge in eine Mail Nachricht umwandeln.';
@override
String get developerModeEnable => 'Entwicklungs-Modus aktivieren';
@override
String get developerShowAsEmail => 'Text zu E-Mail konvertieren';
@override
String get developerShowAsEmailFailed => 'Dieser Text kann nicht in einer MIME Nachricht umgewandelt werden.';
@override
String get designTitle => 'Design Einstellungen';
@override
String get designSectionThemeTitle => 'Modus';
@override
String get designThemeOptionLight => 'Hell';
@override
String get designThemeOptionDark => 'Dunkel';
@override
String get designThemeOptionSystem => 'System';
@override
String get designThemeOptionCustom => 'Selbst definieren';
@override
String get designSectionCustomTitle => 'Der dunkle Modus wird aktiviert';
@override
String designThemeCustomStart(String time) {
return 'von $time';
}
@override
String designThemeCustomEnd(String time) {
return 'bis $time';
}
@override
String get designSectionColorTitle => 'Farbschema';
@override
String get securitySettingsTitle => 'Sicherheit';
@override
String get securitySettingsIntro => 'Passe die Sicherheitseinstellungen deinen persönlichen Ansprüchen an.';
@override
String get securityUnlockWithFaceId => 'Entsicher Maily mit Face ID.';
@override
String get securityUnlockWithTouchId => 'Entsicher Maily mit Touch ID.';
@override
String get securityUnlockReason => 'Entsicher Maily.';
@override
String get securityUnlockDisableReason => 'Entsicher Maily um die Sicherung zu deaktvieren.';
@override
String get securityUnlockNotAvailable => 'Dein Gerät unterstützt keine Biometrie-Absicherung. Vielleicht musst du zuerst die Displaysperre in den Geräteeinstellungen aktivieren.';
@override
String get securityUnlockLabel => 'Maily Absichern';
@override
String get securityUnlockDescriptionTitle => 'Maily Absichern';
@override
String get securityUnlockDescriptionText => 'Du kannst Maily absichern, so dass anderen deine E-Mails auch dann nicht lesen können, wenn sie Zugang zu deinem Gerät haben.';
@override
String get securityLockImmediately => 'Sofort absichern';
@override
String get securityLockAfter5Minutes => 'Nach 5 Minuten absichern';
@override
String get securityLockAfter30Minutes => 'Nach 30 Minuten absichern';
@override
String get lockScreenTitle => 'Maily ist gesichert';
@override
String get lockScreenIntro => 'Maily ist gesichert, bitte authentifiziere dich um weiter zu machen.';
@override
String get lockScreenUnlockAction => 'Entsichern';
@override
String get addAccountTitle => 'Konto hinzufügen';
@override
String get addAccountEmailLabel => 'E-Mail';
@override
String get addAccountEmailHint => 'Deine E-Mail Adresse';
@override
String addAccountResolvingSettingsLabel(String email) {
return 'Suche $email Einstellungen...';
}
@override
String addAccountResolvedSettingsWrongAction(String provider) {
return 'Nicht bei $provider?';
}
@override
String addAccountResolvingSettingsFailedInfo(String email) {
return 'Ich konte die Einstellungen für $email nicht finden. Bitte gehe zurück und ändere die E-Mail Adresse oder gebe die Einstellungen manuell an.';
}
@override
String get addAccountEditManuallyAction => 'Manuell bearbeiten';
@override
String get addAccountPasswordLabel => 'Passwort';
@override
String get addAccountPasswordHint => 'Dein Passwort';
@override
String get addAccountApplicationPasswordRequiredInfo => 'Dieser Anbieter verlangt ein Applikations-spezifisches Passwort.';
@override
String get addAccountApplicationPasswordRequiredButton => 'App Passwort erstellen';
@override
String get addAccountApplicationPasswordRequiredAcknowledged => 'Ich habe bereits ein App Passwort';
@override
String get addAccountVerificationStep => 'Überprüfen';
@override
String get addAccountSetupAccountStep => 'Konto Einrichten';
@override
String addAccountVerifyingSettingsLabel(String email) {
return 'Überprüfe $email...';
}
@override
String addAccountVerifyingSuccessInfo(String email) {
return 'Erfolgreich mit $email angemeldet.';
}
@override
String addAccountVerifyingFailedInfo(String email) {
return 'Leider konnte ich dich nicht anmelden. Überprüfe deine E-Mail $email und dein Passwort.';
}
@override
String addAccountOauthOptionsText(String provider) {
return 'Melde dich mit $provider an oder erstelle ein Applikations-spezifisches Passwort.';
}
@override
String addAccountOauthSignIn(String provider) {
return 'Mit $provider einloggen';
}
@override
String get addAccountOauthSignInGoogle => 'Mit Google einloggen';
@override
String get addAccountOauthSignInWithAppPassword => 'Oder erstelle ein Applikations-Passwort:';
@override
String get accountAddImapAccessSetupMightBeRequired => 'Vielleicht musst Du bei deinem Anbieter den Zugang für E-Mail Apps aktivieren.';
@override
String get addAccountSetupImapAccessButtonLabel => 'E-Mail Zugang aktivieren';
@override
String get addAccountNameOfUserLabel => 'Dein Name';
@override
String get addAccountNameOfUserHint => 'Name, den Empfänger:innen sehen';
@override
String get addAccountNameOfAccountLabel => 'Konto Name';
@override
String get addAccountNameOfAccountHint => 'Gebe den Namen des Kontos an';
@override
String editAccountTitle(String name) {
return 'Bearbeite $name';
}
@override
String editAccountFailureToConnectInfo(String name) {
return 'Maily konnte $name nicht erreichen.';
}
@override
String get editAccountFailureToConnectRetryAction => 'Wiederholen';
@override
String get editAccountFailureToConnectChangePasswordAction => 'Passwort ändern';
@override
String get editAccountFailureToConnectFixedTitle => 'Verbunden';
@override
String get editAccountFailureToConnectFixedInfo => 'Das Konto ist wieder verbunden.';
@override
String get editAccountIncludeInUnifiedLabel => 'zu \"Alle Konten\" hinzufügen';
@override
String editAccountAliasLabel(String email) {
return 'Alias E-Mail Adressen für $email:';
}
@override
String get editAccountNoAliasesInfo => 'Du hast noch keine bekannten Alias E-Mail Adressen für dieses Konto.';
@override
String editAccountAliasRemoved(String email) {
return '$email Alias gelöscht';
}
@override
String get editAccountAddAliasAction => 'Alias hinzufügen';
@override
String get editAccountPlusAliasesSupported => 'Unterstützt + Aliase';
@override
String get editAccountCheckPlusAliasAction => 'Teste Unterstützung für + Aliase';
@override
String get editAccountBccMyself => 'Setze mich auf BCC';
@override
String get editAccountBccMyselfDescriptionTitle => 'Setze mich auf CC';
@override
String get editAccountBccMyselfDescriptionText => 'Du kannst Dir selbst eine \"BCC\" Kopie von jeder Nachricht schicken, die du von diesem Konto verschickst. Normalerweise ist das nicht nötig und nicht gewollt, weil alle gesendeten Nachrichten im\"Gesendete Nachrichten\" Ordner gespeichert werden.';
@override
String get editAccountServerSettingsAction => 'Bearbeite Server Einstellungen';
@override
String get editAccountDeleteAccountAction => 'Lösche Konto';
@override
String get editAccountDeleteAccountConfirmationTitle => 'Bestätige';
@override
String editAccountDeleteAccountConfirmationQuery(String name) {
return 'Möchtest du das Konto $name löschen?';
}
@override
String editAccountTestPlusAliasTitle(String name) {
return '+ Aliase für $name';
}
@override
String get editAccountTestPlusAliasStepIntroductionTitle => 'Einleitung';
@override
String editAccountTestPlusAliasStepIntroductionText(String accountName, String example) {
return 'Dein Konto $accountName könnte sogenannte + Aliase wie $example unterstützen.\nEin + Alias hilft dir Deine Identität zu schützen und kann gegen Spam helfen.\nUm dies zu testen, wird eine Nachricht an diese generierte Adresse gesendet. Wenn sie ankommt, dann unterstützt dein Anbieter + Aliase und du kannst leicht neue generieren wenn Du eine E-Mail schreibst.';
}
@override
String get editAccountTestPlusAliasStepTestingTitle => 'Testen';
@override
String get editAccountTestPlusAliasStepResultTitle => 'Ergebnis';
@override
String editAccountTestPlusAliasStepResultSuccess(String name) {
return 'Dein Konto $name unterstütz + Aliase.';
}
@override
String editAccountTestPlusAliasStepResultNoSuccess(String name) {
return 'Dein Konto $name unterstütz leider keine + Aliase.';
}
@override
String get editAccountAddAliasTitle => 'Alias hinzufügen';
@override
String get editAccountEditAliasTitle => 'Alias bearbeiten';
@override
String get editAccountAliasAddAction => 'Hinzufügen';
@override
String get editAccountAliasUpdateAction => 'Ändern';
@override
String get editAccountEditAliasNameLabel => 'Alias Name';
@override
String get editAccountEditAliasEmailLabel => 'Alias E-Mail';
@override
String get editAccountEditAliasEmailHint => 'Deine Alias E-Mail Adresse';
@override
String editAccountEditAliasDuplicateError(String email) {
return 'Es gibt bereits einen Alias mit $email.';
}
@override
String get editAccountEnableLogging => 'Log aktivieren';
@override
String get editAccountLoggingEnabled => 'Log aktiviert, bitte neu starten';
@override
String get editAccountLoggingDisabled => 'Log de-aktiviert, bitte neu starten';
@override
String get accountDetailsFallbackTitle => 'Server Einstellungen';
@override
String get errorTitle => 'Fehler';
@override
String get accountProviderStepTitle => 'E-Mail Service Anbieter';
@override
String get accountProviderCustom => 'Anderer E-Mail Service';
@override
String accountDetailsErrorHostProblem(String incomingHost, String outgoingHost) {
return 'Maily kann den angegeben Server nicht erreich. Bitte überprüfe die Einstellugen des Posteingang-Servers \"$incomingHost\" und des Postausgang-Servers \"$outgoingHost\".';
}
@override
String accountDetailsErrorLoginProblem(String userName, String password) {
return 'Anmeldung fehlgeschlagen. Bitte überprüfe den Login-Namen \"$userName\" und das Passwort \"$password\".';
}
@override
String get accountDetailsUserNameLabel => 'Login Name';
@override
String get accountDetailsUserNameHint => 'Dein Login, falls es nicht die E-Mail ist';
@override
String get accountDetailsPasswordLabel => 'Login Passwort';
@override
String get accountDetailsPasswordHint => 'Dein Passwort';
@override
String get accountDetailsBaseSectionTitle => 'Basis Einstellungen';
@override
String get accountDetailsIncomingLabel => 'Posteingangs-Server';
@override
String get accountDetailsIncomingHint => 'Domäne wie imap.domain.de';
@override
String get accountDetailsOutgoingLabel => 'Postausgangs-Server';
@override
String get accountDetailsOutgoingHint => 'Domäne wie smtp.domain.de';
@override
String get accountDetailsAdvancedIncomingSectionTitle => 'Erweiterte Posteingang Einstellungen';
@override
String get accountDetailsIncomingServerTypeLabel => 'Typ des Posteingang Servers:';
@override
String get accountDetailsOptionAutomatic => 'automatisch';
@override
String get accountDetailsIncomingSecurityLabel => 'Posteingang Sicherheit:';
@override
String get accountDetailsSecurityOptionNone => 'Plain (keine Verschlüsselung)';
@override
String get accountDetailsIncomingPortLabel => 'Posteingang Port';
@override
String get accountDetailsPortHint => 'Leer lassen um automatisch finden zu lassen';
@override
String get accountDetailsIncomingUserNameLabel => 'Posteingang Login-Name';
@override
String get accountDetailsAlternativeUserNameHint => 'Login, falls abweichend von oben';
@override
String get accountDetailsIncomingPasswordLabel => 'Posteingang Passwort';
@override
String get accountDetailsAlternativePasswordHint => 'Passwort, falls abweichend von oben';
@override
String get accountDetailsAdvancedOutgoingSectionTitle => 'Erweiterte Postausgang Einstellungen';
@override
String get accountDetailsOutgoingServerTypeLabel => 'Typ des Postausgang Servers:';
@override
String get accountDetailsOutgoingSecurityLabel => 'Postausgang Sicherheit:';
@override
String get accountDetailsOutgoingPortLabel => 'Postausgang Port';
@override
String get accountDetailsOutgoingUserNameLabel => 'Postausgang Login-Name';
@override
String get accountDetailsOutgoingPasswordLabel => 'Postausgang Passwort';
@override
String get composeTitleNew => 'Neu';
@override
String get composeTitleForward => 'Weiterleitung';
@override
String get composeTitleReply => 'Antwort';
@override
String get composeEmptyMessage => 'Leere Nachricht';
@override
String get composeWarningNoSubject => 'Du hast kein Betreff geschrieben. Möchtest du die Nachricht ohne Betreff senden?';
@override
String get composeActionSentWithoutSubject => 'Senden';
@override
String get composeMailSendSuccess => 'Gesendet 😊';
@override
String composeSendErrorInfo(String details) {
return 'Leider konnte die E-Mail nicht versendet werden.\nDer Postausgang Server liefert folgende Antwort:\n$details';
}
@override
String get composeRequestReadReceiptAction => 'Lesebestätigung anfordern';
@override
String get composeSaveDraftAction => 'Als Entwurf speichern';
@override
String get composeMessageSavedAsDraft => 'Entwurf gespeichert';
@override
String composeMessageSavedAsDraftErrorInfo(String details) {
return 'Der Entwurf konnte nicht gespeichert werden.\nDie Fehlermeldung lautet:\n$details';
}
@override
String get composeConvertToPlainTextEditorAction => 'Zu Text-Nachricht konvertieren';
@override
String get composeConvertToHtmlEditorAction => 'Zu HTML-Nachricht konvertieren';
@override
String get composeContinueEditingAction => 'Weiter bearbeiten';
@override
String get composeCreatePlusAliasAction => 'Neuen + Alias erstellen...';
@override
String get composeSenderHint => 'Absender:in';
@override
String get composeRecipientHint => 'E-Mails der Empfänger:innen';
@override
String get composeSubjectLabel => 'Betreff';
@override
String get composeSubjectHint => 'Betreff der Nachricht';
@override
String get composeAddAttachmentAction => 'Hinzufügen';
@override
String composeRemoveAttachmentAction(String name) {
return '$name entfernen';
}
@override
String get composeLeftByMistake => 'Aus Versehen verlassen?';
@override
String get attachTypeFile => 'Datei';
@override
String get attachTypePhoto => 'Foto';
@override
String get attachTypeVideo => 'Video';
@override
String get attachTypeAudio => 'Audio';
@override
String get attachTypeLocation => 'Ort';
@override
String get attachTypeGif => 'Animiertes Gif';
@override
String get attachTypeGifSearch => 'in GIPHY suchen';
@override
String get attachTypeSticker => 'Sticker';
@override
String get attachTypeStickerSearch => 'in GIPHY suchen';
@override
String get attachTypeAppointment => 'Termin';
@override
String get languageSettingTitle => 'Sprache (Language)';
@override
String get languageSettingLabel => 'Währe die Sprache für Maily:';
@override
String get languageSettingSystemOption => 'Systemsprache';
@override
String get languageSettingConfirmationTitle => 'Deutsch für Maily nutzen?';
@override
String get languageSettingConfirmationQuery => 'Bitte bestätige, dass deutsch als Sprache verwendet werden soll.';
@override
String get languageSetInfo => 'Maily ist nun auf deutsch. Bitte starte die App neu.';
@override
String get languageSystemSetInfo => 'Maily wird nun die Systemsprache oder englisch nutzen, wenn die Systemprache nicht unterstützt wird. Bitte starte die App neu.';
@override
String get swipeSettingTitle => 'Wischgesten';
@override
String get swipeSettingLeftToRightLabel => 'Von links nach rechts wischen';
@override
String get swipeSettingRightToLeftLabel => 'Von rechts nach links wischen';
@override
String get swipeSettingChangeAction => 'Ändern';
@override
String get signatureSettingsTitle => 'Signatur';
@override
String get signatureSettingsComposeActionsInfo => 'Aktiviere die Signatur für folgende Nachrichten:';
@override
String get signatureSettingsAccountInfo => 'Du kannst Signaturen für Konten in den Konten-Einstellungen festlegen.';
@override
String signatureSettingsAddForAccount(String account) {
return 'Signature für $account hinzufügen';
}
@override
String get defaultSenderSettingsTitle => 'Standard Absender';
@override
String get defaultSenderSettingsLabel => 'Wähle den Absender für neue Nachrichten aus.';
@override
String defaultSenderSettingsFirstAccount(String email) {
return 'Erstes Konto ($email)';
}
@override
String get defaultSenderSettingsAliasInfo => 'Du kannst Alias E-Mail Adressen in den [AS] festlegen.';
@override
String get defaultSenderSettingsAliasAccountSettings => 'Konto-Einstellungen';
@override
String get replySettingsTitle => 'Nachrichten Format';
@override
String get replySettingsIntro => 'In welchem Format möchtest du Nachrichten schreiben?';
@override
String get replySettingsFormatHtml => 'Immer HTML';
@override
String get replySettingsFormatSameAsOriginal => 'Im selben Format wie die Orignal-Nachricht';
@override
String get replySettingsFormatPlainText => 'Immer nur Text';
@override
String get moveTitle => 'Nachricht verschieben';
@override
String moveSuccess(String mailbox) {
return 'In $mailbox verschoben.';
}
@override
String get editorArtInputLabel => 'Deine Eingabe';
@override
String get editorArtInputHint => 'Hier Text eingeben';
@override
String get editorArtWaitingForInputHint => 'warte auf Eingabe...';
@override
String get fontSerifBold => 'Serif fett';
@override
String get fontSerifItalic => 'Serif kursiv';
@override
String get fontSerifBoldItalic => 'Serif fett kursiv';
@override
String get fontSans => 'Sans';
@override
String get fontSansBold => 'Sans fett';
@override
String get fontSansItalic => 'Sans kursiv';
@override
String get fontSansBoldItalic => 'Sans fett kursiv';
@override
String get fontScript => 'Skript';
@override
String get fontScriptBold => 'Script fett';
@override
String get fontFraktur => 'Fraktur';
@override
String get fontFrakturBold => 'Fraktur fett';
@override
String get fontMonospace => 'Monospace';
@override
String get fontFullwidth => 'Fullwidth';
@override
String get fontDoublestruck => 'Doppelt gestrichen';
@override
String get fontCapitalized => 'Grossbuchstaben';
@override
String get fontCircled => 'Eingekreist';
@override
String get fontParenthesized => 'Geklammert';
@override
String get fontUnderlinedSingle => 'Unterstrichen';
@override
String get fontUnderlinedDouble => 'Doppelt unterstrichen';
@override
String get fontStrikethroughSingle => 'Durchgestrichen';
@override
String get fontCrosshatch => 'Crosshatch';
@override
String accountLoadError(String name) {
return 'Keine Verbindung mit $name möglich. Wurde vielleicht das Passwort geändert?';
}
@override
String get accountLoadErrorEditAction => 'Konto bearbeiten';
@override
String get extensionsTitle => 'Erweiterungen';
@override
String get extensionsIntro => 'Mit Erweiterungen können E-Mail-Dienstleister, Firmen und Entwickler:innen Maily mit hilfreichen Funktionen ergänzen.';
@override
String get extensionsLearnMoreAction => 'Lerne mehr über Erweiterungen';
@override
String get extensionsReloadAction => 'Erweiterungen neu laden';
@override
String get extensionDeactivateAllAction => 'Alle Erweiterungen deaktivieren';
@override
String get extensionsManualAction => 'Manuell laden';
@override
String get extensionsManualUrlLabel => 'Url der Erweiterung';
@override
String extensionsManualLoadingError(String url) {
return 'Es kann keine Erweiterung von \"$url\" heruntergeladen werden.';
}
@override
String get icalendarAcceptTentatively => 'Vorbehaltlich';
@override
String get icalendarActionChangeParticipantStatus => 'Ändern';
@override
String get icalendarLabelSummary => 'Titel';
@override
String get icalendarNoSummaryInfo => '(kein Titel)';
@override
String get icalendarLabelDescription => 'Beschreibung';
@override
String get icalendarLabelStart => 'Start';
@override
String get icalendarLabelEnd => 'Ende';
@override
String get icalendarLabelDuration => 'Dauer';
@override
String get icalendarLabelLocation => 'Ort';
@override
String get icalendarLabelTeamsUrl => 'Link';
@override
String get icalendarLabelRecurrenceRule => 'Wiederholung';
@override
String get icalendarLabelParticipants => 'Teilnehmer';
@override
String get icalendarParticipantStatusNeedsAction => 'Du wirst gebeten, diese Einladung zu beantworten.';
@override
String get icalendarParticipantStatusAccepted => 'Du hast die Einladung akzeptiert.';
@override
String get icalendarParticipantStatusDeclined => 'Du hast die Einladung abgelehnt.';
@override
String get icalendarParticipantStatusAcceptedTentatively => 'Du hast die Einladung vorbehaltlich akzeptiert.';
@override
String get icalendarParticipantStatusDelegated => 'Du hast die Teilnahme delegiert.';
@override
String get icalendarParticipantStatusInProcess => 'Die Aufgabe wird bearbeitet.';
@override
String get icalendarParticipantStatusPartial => 'Die Aufgabe ist teilweise erledigt.';
@override
String get icalendarParticipantStatusCompleted => 'Die Aufgabe ist erledigt.';
@override
String get icalendarParticipantStatusOther => 'Der Status ist unbekannt.';
@override
String get icalendarParticipantStatusChangeTitle => 'Dein Status';
@override
String get icalendarParticipantStatusChangeText => 'Möchtest Du an diese Einladung annehmen?';
@override
String icalendarParticipantStatusSentFailure(String details) {
return 'Antwort kann nicht gesendet werrden.\nDer Server hat mit den folgenden Details geantwortet:\n$details';
}
@override
String get icalendarExportAction => 'Exportieren';
@override
String icalendarReplyStatusNeedsAction(String attendee) {
return '$attendee hat diese Einladung nicht beantwortet.';
}
@override
String icalendarReplyStatusAccepted(String attendee) {
return '$attendee hat die Einladung akzeptiert.';
}
@override
String icalendarReplyStatusDeclined(String attendee) {
return '$attendee hat die Einladung abgelehnt.';
}
@override
String icalendarReplyStatusAcceptedTentatively(String attendee) {
return '$attendee hat die Einladung vorbehaltlich akzeptiert.';
}
@override
String icalendarReplyStatusDelegated(String attendee) {
return '$attendee hat die Teilnahme delegiert.';
}
@override
String icalendarReplyStatusInProcess(String attendee) {
return '$attendee hat mit der Aufgabe begonnen.';
}
@override
String icalendarReplyStatusPartial(String attendee) {
return '$attendee hat die Aufgabe teilweise erledigt.';
}
@override
String icalendarReplyStatusCompleted(String attendee) {
return '$attendee hat die Aufgabe erledigt.';
}
@override
String icalendarReplyStatusOther(String attendee) {
return '$attendee hat mit einem unbekannten Status geantwortet.';
}
@override
String get icalendarReplyWithoutParticipants => 'Diese Antwort enthält keine Teilnehmer:innen.';
@override
String icalendarReplyWithoutStatus(String attendee) {
return '$attendee hat eine Antwort ohne Teilnahme-Status gesendet.';
}
@override
String get composeAppointmentTitle => 'Einladung erstellen';
@override
String get composeAppointmentLabelDay => 'Tag';
@override
String get composeAppointmentLabelTime => 'Zeit';
@override
String get composeAppointmentLabelAllDayEvent => 'Ganztägiger Termin';
@override
String get composeAppointmentLabelRepeat => 'Wiederholen';
@override
String get composeAppointmentLabelRepeatOptionNever => 'Nie';
@override
String get composeAppointmentLabelRepeatOptionDaily => 'Täglich';
@override
String get composeAppointmentLabelRepeatOptionWeekly => 'Wöchentlich';
@override
String get composeAppointmentLabelRepeatOptionMonthly => 'Monatlich';
@override
String get composeAppointmentLabelRepeatOptionYearly => 'Jährlich';
@override
String get composeAppointmentRecurrenceFrequencyLabel => 'Frequenz';
@override
String get composeAppointmentRecurrenceIntervalLabel => 'Intervall';
@override
String get composeAppointmentRecurrenceDaysLabel => 'An Tagen';
@override
String get composeAppointmentRecurrenceUntilLabel => 'Bis';
@override
String get composeAppointmentRecurrenceUntilOptionUnlimited => 'Unlimitiert';
@override
String composeAppointmentRecurrenceUntilOptionRecommended(String duration) {
return 'Empfohlen ($duration)';
}
@override
String get composeAppointmentRecurrenceUntilOptionSpecificDate => 'Bestimmtes Datum';
@override
String composeAppointmentRecurrenceMonthlyOnDayOfMonth(int day) {
final intl.NumberFormat dayNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String dayString = dayNumberFormat.format(day);
return 'Am $dayString. Tag des Monats';
}
@override
String get composeAppointmentRecurrenceMonthlyOnWeekDay => 'Am Wochentag des Monats';
@override
String get composeAppointmentRecurrenceFirst => 'Erster';
@override
String get composeAppointmentRecurrenceSecond => 'Zweiter';
@override
String get composeAppointmentRecurrenceThird => 'Dritter';
@override
String get composeAppointmentRecurrenceLast => 'Letzter';
@override
String get composeAppointmentRecurrenceSecondLast => 'Vorletzter';
@override
String durationYears(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Jahre',
one: '1 Jahr',
);
return '$_temp0';
}
@override
String durationMonths(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Monate',
one: '1 Monat',
);
return '$_temp0';
}
@override
String durationWeeks(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Wochen',
one: '1 Woche',
);
return '$_temp0';
}
@override
String durationDays(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Tage',
one: '1 Tag',
);
return '$_temp0';
}
@override
String durationHours(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Stunden',
one: '1 Stunde',
);
return '$_temp0';
}
@override
String durationMinutes(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString Minuten',
one: '1 Minute',
);
return '$_temp0';
}
@override
String get durationEmpty => 'Keine Dauer';
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/localization/provider.dart
|
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../settings/provider.dart';
import 'app_localizations.g.dart';
import 'app_localizations_en.g.dart';
part 'provider.g.dart';
@Riverpod(keepAlive: true)
class CurrentAppLocalization extends _$CurrentAppLocalization {
static _LocaleObserver? _observer;
@override
AppLocalizations build() {
final languageTag =
ref.watch(settingsProvider.select((settings) => settings.languageTag));
final locale = languageTag != null
? Locale(languageTag)
: PlatformDispatcher.instance.locale;
state = resolve(locale);
final binding = WidgetsBinding.instance;
final existingObserver = _observer;
if (languageTag != null) {
if (existingObserver != null) {
binding.removeObserver(existingObserver);
_observer = null;
}
} else {
if (existingObserver == null) {
final newObserver = _LocaleObserver((locales) {
state = resolve(PlatformDispatcher.instance.locale);
});
_observer = newObserver;
binding.addObserver(newObserver);
}
}
ref.onDispose(() {
final observer = _observer;
if (observer != null) {
binding.removeObserver(observer);
}
});
return state;
}
/// Finds the localizations for the given [locale]
AppLocalizations resolve(Locale locale) {
try {
return lookupAppLocalizations(locale);
// ignore: avoid_catching_errors
} on FlutterError {
return AppLocalizationsEn();
}
}
}
/// observed used to notify the caller when the locale changes
class _LocaleObserver extends WidgetsBindingObserver {
_LocaleObserver(this._didChangeLocales);
final void Function(List<Locale>? locales) _didChangeLocales;
@override
void didChangeLocales(List<Locale>? locales) => _didChangeLocales(locales);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/localization/app_localizations.g.dart
|
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart' as intl;
import 'app_localizations_de.g.dart';
import 'app_localizations_en.g.dart';
import 'app_localizations_es.g.dart';
/// Callers can lookup localized strings with an instance of AppLocalizations
/// returned by `AppLocalizations.of(context)`.
///
/// Applications need to include `AppLocalizations.delegate()` in their app's
/// `localizationDelegates` list, and the locales they support in the app's
/// `supportedLocales` list. For example:
///
/// ```dart
/// import 'localization/app_localizations.g.dart';
///
/// return MaterialApp(
/// localizationsDelegates: AppLocalizations.localizationsDelegates,
/// supportedLocales: AppLocalizations.supportedLocales,
/// home: MyApplicationHome(),
/// );
/// ```
///
/// ## Update pubspec.yaml
///
/// Please make sure to update your pubspec.yaml to include the following
/// packages:
///
/// ```yaml
/// dependencies:
/// # Internationalization support.
/// flutter_localizations:
/// sdk: flutter
/// intl: any # Use the pinned version from flutter_localizations
///
/// # Rest of dependencies
/// ```
///
/// ## iOS Applications
///
/// iOS applications define key application metadata, including supported
/// locales, in an Info.plist file that is built into the application bundle.
/// To configure the locales supported by your app, you’ll need to edit this
/// file.
///
/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file.
/// Then, in the Project Navigator, open the Info.plist file under the Runner
/// project’s Runner folder.
///
/// Next, select the Information Property List item, select Add Item from the
/// Editor menu, then select Localizations from the pop-up menu.
///
/// Select and expand the newly-created Localizations item then, for each
/// locale your application supports, add a new item and select the locale
/// you wish to add from the pop-up menu in the Value field. This list should
/// be consistent with the languages listed in the AppLocalizations.supportedLocales
/// property.
abstract class AppLocalizations {
AppLocalizations(String locale) : localeName = intl.Intl.canonicalizedLocale(locale.toString());
final String localeName;
static AppLocalizations? of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();
/// A list of this localizations delegate along with the default localizations
/// delegates.
///
/// Returns a list of localizations delegates containing this delegate along with
/// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
/// and GlobalWidgetsLocalizations.delegate.
///
/// Additional delegates can be added by appending to this list in
/// MaterialApp. This list does not have to be used at all if a custom list
/// of delegates is preferred or required.
static const List<LocalizationsDelegate<dynamic>> localizationsDelegates = <LocalizationsDelegate<dynamic>>[
delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
];
/// A list of this localizations delegate's supported locales.
static const List<Locale> supportedLocales = <Locale>[
Locale('en'),
Locale('de'),
Locale('es')
];
/// Default signature text
///
/// In en, this message translates to:
/// **'Sent with Maily'**
String get signature;
/// Generic cancel action
///
/// In en, this message translates to:
/// **'Cancel'**
String get actionCancel;
/// Generic OK action
///
/// In en, this message translates to:
/// **'OK'**
String get actionOk;
/// Generic done action
///
/// In en, this message translates to:
/// **'Done'**
String get actionDone;
/// Generic next action
///
/// In en, this message translates to:
/// **'Next'**
String get actionNext;
/// Generic skip action
///
/// In en, this message translates to:
/// **'Skip'**
String get actionSkip;
/// Generic undo action
///
/// In en, this message translates to:
/// **'Undo'**
String get actionUndo;
/// Generic delete action
///
/// In en, this message translates to:
/// **'Delete'**
String get actionDelete;
/// Generic accept action
///
/// In en, this message translates to:
/// **'Accept'**
String get actionAccept;
/// Generic decline action
///
/// In en, this message translates to:
/// **'Decline'**
String get actionDecline;
/// Generic edit action
///
/// In en, this message translates to:
/// **'Edit'**
String get actionEdit;
/// Copy action for email addresses
///
/// In en, this message translates to:
/// **'Copy'**
String get actionAddressCopy;
/// Compose action for email addresses
///
/// In en, this message translates to:
/// **'New message'**
String get actionAddressCompose;
/// Search action for email addresses
///
/// In en, this message translates to:
/// **'Search'**
String get actionAddressSearch;
/// Message shown on splash screen while loading
///
/// In en, this message translates to:
/// **'Maily starting...'**
String get splashLoading1;
/// Message shown on splash screen while loading
///
/// In en, this message translates to:
/// **'Getting your Maily engine ready...'**
String get splashLoading2;
/// Message shown on splash screen while loading
///
/// In en, this message translates to:
/// **'Launching Maily in 10, 9, 8...'**
String get splashLoading3;
/// Welcome panel title
///
/// In en, this message translates to:
/// **'Maily'**
String get welcomePanel1Title;
/// Welcome message shown on first panel
///
/// In en, this message translates to:
/// **'Welcome to Maily, your friendly and fast email helper!'**
String get welcomePanel1Text;
/// Welcome panel title
///
/// In en, this message translates to:
/// **'Accounts'**
String get welcomePanel2Title;
/// Welcome message shown on second panel
///
/// In en, this message translates to:
/// **'Manage unlimited email accounts. Read and search for mails in all your accounts at once.'**
String get welcomePanel2Text;
/// Welcome panel title
///
/// In en, this message translates to:
/// **'Swipe & Long-Press'**
String get welcomePanel3Title;
/// Welcome message shown on third panel
///
/// In en, this message translates to:
/// **'Swipe your mails to delete them or to mark them read. Long-press a message to select and manage several messages.'**
String get welcomePanel3Text;
/// Welcome panel title
///
/// In en, this message translates to:
/// **'Keep your Inbox clean'**
String get welcomePanel4Title;
/// Welcome message shown on fourth panel
///
/// In en, this message translates to:
/// **'Unsubscribe newsletters with just one tap.'**
String get welcomePanel4Text;
/// Button showing login option
///
/// In en, this message translates to:
/// **'Sign in to your mail account'**
String get welcomeActionSignIn;
/// Hint shown in empty search field
///
/// In en, this message translates to:
/// **'Your search'**
String get homeSearchHint;
/// Action to show mails as stack
///
/// In en, this message translates to:
/// **'Show as stack'**
String get homeActionsShowAsStack;
/// Action to show mails as list
///
/// In en, this message translates to:
/// **'Show as list'**
String get homeActionsShowAsList;
/// Message shown when there are no messages in the folder
///
/// In en, this message translates to:
/// **'All done!\n\nThere are no messages in this folder.'**
String get homeEmptyFolderMessage;
/// Message shown when there are no messages found in a search query
///
/// In en, this message translates to:
/// **'No messages found.'**
String get homeEmptySearchMessage;
/// Title of confirmation dialog when deleting all messages
///
/// In en, this message translates to:
/// **'Confirm'**
String get homeDeleteAllTitle;
/// Question in confirmation dialog when deleting all messages
///
/// In en, this message translates to:
/// **'Really delete all messages?'**
String get homeDeleteAllQuestion;
/// Action to tap to delete all messages (must be short).
///
/// In en, this message translates to:
/// **'Delete all'**
String get homeDeleteAllAction;
/// Option to remove deleted messages from disk.
///
/// In en, this message translates to:
/// **'Scrub messages'**
String get homeDeleteAllScrubOption;
/// Message shown after all messages have been deleted.
///
/// In en, this message translates to:
/// **'All messages deleted.'**
String get homeDeleteAllSuccess;
/// Action to tap to mark all messages as seen / read (must be short).
///
/// In en, this message translates to:
/// **'All read'**
String get homeMarkAllSeenAction;
/// Action to tap to mark all messages as unseen / unread (must be short).
///
/// In en, this message translates to:
/// **'All unread'**
String get homeMarkAllUnseenAction;
/// Tooltip for 'compose new message' floating action button.
///
/// In en, this message translates to:
/// **'New message'**
String get homeFabTooltip;
/// Title shown while message source itself is being loaded.
///
/// In en, this message translates to:
/// **'Loading...'**
String get homeLoadingMessageSourceTitle;
/// Message shown while loading message.
///
/// In en, this message translates to:
/// **'loading {name}...'**
String homeLoading(String name);
/// Swipe action for marking a message as read / unread.
///
/// In en, this message translates to:
/// **'Mark as read/unread'**
String get swipeActionToggleRead;
/// Swipe action for deleting a message.
///
/// In en, this message translates to:
/// **'Delete'**
String get swipeActionDelete;
/// Swipe action for moving a message to junk.
///
/// In en, this message translates to:
/// **'Mark as junk'**
String get swipeActionMarkJunk;
/// Swipe action for moving a message to archive.
///
/// In en, this message translates to:
/// **'Archive'**
String get swipeActionArchive;
/// Swipe action for marking a message as flagged / unflagged.
///
/// In en, this message translates to:
/// **'Toggle flag'**
String get swipeActionFlag;
/// Message shown after moving messages to junk. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{One message marked as junk} other{Marked {number} messages as junk}}'**
String multipleMovedToJunk(int number);
/// Message shown after moving messages from junk, trash or archive back to the Inbox. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{Moved one message to inbox} other{Moved {number} messages to inbox}}'**
String multipleMovedToInbox(int number);
/// Message shown after moving messages to archive. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{Archived one message} other{Archived {number} messages}}'**
String multipleMovedToArchive(int number);
/// Message shown after moving messages to trash. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{Deleted one message} other{Deleted {number} messages}}'**
String multipleMovedToTrash(int number);
/// Short info shown when a multiple message action is triggered without selecting at least one message first.
///
/// In en, this message translates to:
/// **'Please select messages first.'**
String get multipleSelectionNeededInfo;
/// Error message when the selection action failed.
///
/// In en, this message translates to:
/// **'Unable to perform action\nDetails: {details}'**
String multipleSelectionActionFailed(String details);
/// Title of move dialog for multiple messages. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{Move message} other{Move {number} messages}}'**
String multipleMoveTitle(int number);
/// Action for several messages.
///
/// In en, this message translates to:
/// **'Mark as read'**
String get messageActionMultipleMarkSeen;
/// Action for several messages.
///
/// In en, this message translates to:
/// **'Mark as unread'**
String get messageActionMultipleMarkUnseen;
/// Action for several messages.
///
/// In en, this message translates to:
/// **'Flag messages'**
String get messageActionMultipleMarkFlagged;
/// Action for several messages.
///
/// In en, this message translates to:
/// **'Unflag messages'**
String get messageActionMultipleMarkUnflagged;
/// No description provided for @messageActionViewInSafeMode.
///
/// In en, this message translates to:
/// **'View without external content'**
String get messageActionViewInSafeMode;
/// Shown as replacement when there is no known sender of a message.
///
/// In en, this message translates to:
/// **'<no sender>'**
String get emailSenderUnknown;
/// Date range title.
///
/// In en, this message translates to:
/// **'future'**
String get dateRangeFuture;
/// Date range title.
///
/// In en, this message translates to:
/// **'tomorrow'**
String get dateRangeTomorrow;
/// Date range title.
///
/// In en, this message translates to:
/// **'today'**
String get dateRangeToday;
/// Date range title.
///
/// In en, this message translates to:
/// **'yesterday'**
String get dateRangeYesterday;
/// Date range title.
///
/// In en, this message translates to:
/// **'this week'**
String get dateRangeCurrentWeek;
/// Date range title.
///
/// In en, this message translates to:
/// **'last week'**
String get dateRangeLastWeek;
/// Date range title.
///
/// In en, this message translates to:
/// **'this month'**
String get dateRangeCurrentMonth;
/// Date range title.
///
/// In en, this message translates to:
/// **'last month'**
String get dateRangeLastMonth;
/// Date range title.
///
/// In en, this message translates to:
/// **'this year'**
String get dateRangeCurrentYear;
/// Date range title.
///
/// In en, this message translates to:
/// **'long ago'**
String get dateRangeLongAgo;
/// Unknown date.
///
/// In en, this message translates to:
/// **'undefined'**
String get dateUndefined;
/// Message data is today.
///
/// In en, this message translates to:
/// **'today'**
String get dateDayToday;
/// Message data is yesterday.
///
/// In en, this message translates to:
/// **'yesterday'**
String get dateDayYesterday;
/// Message data is a recent weekday.
///
/// In en, this message translates to:
/// **'last {day}'**
String dateDayLastWeekday(String day);
/// Menu entry for about.
///
/// In en, this message translates to:
/// **'About Maily'**
String get drawerEntryAbout;
/// Menu entry for settings.
///
/// In en, this message translates to:
/// **'Settings'**
String get drawerEntrySettings;
/// Title shown for accounts drop down. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{One account} other{{number} accounts}}'**
String drawerAccountsSectionTitle(int number);
/// Menu entry for adding a new account.
///
/// In en, this message translates to:
/// **'Add account'**
String get drawerEntryAddAccount;
/// Name of unified account.
///
/// In en, this message translates to:
/// **'Unified account'**
String get unifiedAccountName;
/// Folder name of unified account.
///
/// In en, this message translates to:
/// **'Unified Inbox'**
String get unifiedFolderInbox;
/// Folder name of unified account.
///
/// In en, this message translates to:
/// **'Unified Sent'**
String get unifiedFolderSent;
/// Folder name of unified account.
///
/// In en, this message translates to:
/// **'Unified Drafts'**
String get unifiedFolderDrafts;
/// Folder name of unified account.
///
/// In en, this message translates to:
/// **'Unified Trash'**
String get unifiedFolderTrash;
/// Folder name of unified account.
///
/// In en, this message translates to:
/// **'Unified Archive'**
String get unifiedFolderArchive;
/// Folder name of unified account.
///
/// In en, this message translates to:
/// **'Unified Junk'**
String get unifiedFolderJunk;
/// Folder name.
///
/// In en, this message translates to:
/// **'Inbox'**
String get folderInbox;
/// Folder name.
///
/// In en, this message translates to:
/// **'Sent'**
String get folderSent;
/// Folder name.
///
/// In en, this message translates to:
/// **'Drafts'**
String get folderDrafts;
/// Folder name.
///
/// In en, this message translates to:
/// **'Trash'**
String get folderTrash;
/// Folder name.
///
/// In en, this message translates to:
/// **'Archive'**
String get folderArchive;
/// Folder name.
///
/// In en, this message translates to:
/// **'Junk'**
String get folderJunk;
/// Folder name for a message source without a name.
///
/// In en, this message translates to:
/// **'Unknown'**
String get folderUnknown;
/// Show contents of a message on a separate screen.
///
/// In en, this message translates to:
/// **'View contents'**
String get viewContentsAction;
/// Show source code of a message.
///
/// In en, this message translates to:
/// **'View source'**
String get viewSourceAction;
/// Info shown when an email could not be downloaded.
///
/// In en, this message translates to:
/// **'Message could not be downloaded.'**
String get detailsErrorDownloadInfo;
/// Retry action shown when an email could not be downloaded.
///
/// In en, this message translates to:
/// **'Retry'**
String get detailsErrorDownloadRetry;
/// Label for sender(s) of email.
///
/// In en, this message translates to:
/// **'From'**
String get detailsHeaderFrom;
/// Label for [to] recipient(s) of email.
///
/// In en, this message translates to:
/// **'To'**
String get detailsHeaderTo;
/// Label for [CC] - carbon copy - recipient(s) of email.
///
/// In en, this message translates to:
/// **'CC'**
String get detailsHeaderCc;
/// Label for [BCC] - blind carbon copy - recipient(s) of email.
///
/// In en, this message translates to:
/// **'BCC'**
String get detailsHeaderBcc;
/// Label for date of email.
///
/// In en, this message translates to:
/// **'Date'**
String get detailsHeaderDate;
/// Shown instead of the subject when it is undefined.
///
/// In en, this message translates to:
/// **'<without subject>'**
String get subjectUndefined;
/// Action for showing images. Only visible when external images are blocked.
///
/// In en, this message translates to:
/// **'Show images'**
String get detailsActionShowImages;
/// Action shown for unsubscribable newsletter.
///
/// In en, this message translates to:
/// **'Unsubscribe'**
String get detailsNewsletterActionUnsubscribe;
/// Action shown after re-subscribable newsletter has been unsubscribed.
///
/// In en, this message translates to:
/// **'Re-subscribe'**
String get detailsNewsletterActionResubscribe;
/// Status shown for unsubscribed newsletter.
///
/// In en, this message translates to:
/// **'Unsubscribed'**
String get detailsNewsletterStatusUnsubscribed;
/// Title for unsubscribe newsletter dialog.
///
/// In en, this message translates to:
/// **'Unsubscribe'**
String get detailsNewsletterUnsubscribeDialogTitle;
/// Question for unsubscribe newsletter dialog.
///
/// In en, this message translates to:
/// **'Do you want to unsubscribe from the mailing list {listName}?'**
String detailsNewsletterUnsubscribeDialogQuestion(String listName);
/// Action for unsubscribe newsletter dialog.
///
/// In en, this message translates to:
/// **'Unsubscribe'**
String get detailsNewsletterUnsubscribeDialogAction;
/// Title for dialog after unsubscribing newsletter successfully.
///
/// In en, this message translates to:
/// **'Unsubscribed'**
String get detailsNewsletterUnsubscribeSuccessTitle;
/// Text confirmation after successfully unsubscribing a newsletter.
///
/// In en, this message translates to:
/// **'You are now unsubscribed from the mailing list {listName}.'**
String detailsNewsletterUnsubscribeSuccessMessage(String listName);
/// Title for dialog after unsubscribing newsletter failed.
///
/// In en, this message translates to:
/// **'Not unsubscribed'**
String get detailsNewsletterUnsubscribeFailureTitle;
/// Text confirmation after unsubscribing a newsletter failed.
///
/// In en, this message translates to:
/// **'Sorry, but I was unable to unsubscribe you from {listName} automatically.'**
String detailsNewsletterUnsubscribeFailureMessage(String listName);
/// Title for re-subscribe newsletter dialog.
///
/// In en, this message translates to:
/// **'Re-subscribe'**
String get detailsNewsletterResubscribeDialogTitle;
/// Question for re-subscribe newsletter dialog.
///
/// In en, this message translates to:
/// **'Do you want to subscribe to this mailing list {listName} again?'**
String detailsNewsletterResubscribeDialogQuestion(String listName);
/// Action for re-subscribe newsletter dialog.
///
/// In en, this message translates to:
/// **'Subscribe'**
String get detailsNewsletterResubscribeDialogAction;
/// Title for dialog after re-subscribed newsletter successfully.
///
/// In en, this message translates to:
/// **'Subscribed'**
String get detailsNewsletterResubscribeSuccessTitle;
/// Text confirmation after successfully re-subscribing a newsletter.
///
/// In en, this message translates to:
/// **'You are now subscribed to the mailing list {listName} again.'**
String detailsNewsletterResubscribeSuccessMessage(String listName);
/// Title for dialog after re-subscribing newsletter failed.
///
/// In en, this message translates to:
/// **'Not subscribed'**
String get detailsNewsletterResubscribeFailureTitle;
/// Text confirmation after re-subscribing a newsletter failed.
///
/// In en, this message translates to:
/// **'Sorry, but the subscribe request has failed for mailing list {listName}.'**
String detailsNewsletterResubscribeFailureMessage(String listName);
/// Action to send the read receipt for the shown message.
///
/// In en, this message translates to:
/// **'Send read receipt'**
String get detailsSendReadReceiptAction;
/// Status after sending the read receipt for the shown message.
///
/// In en, this message translates to:
/// **'Read receipt sent ✔'**
String get detailsReadReceiptSentStatus;
/// Message subject for read receipts.
///
/// In en, this message translates to:
/// **'Read receipt'**
String get detailsReadReceiptSubject;
/// Open action for attachments without interactive viewer.
///
/// In en, this message translates to:
/// **'Open'**
String get attachmentActionOpen;
/// Text shown when downloaded attachment could not be decoded.
///
/// In en, this message translates to:
/// **'This attachment has an unsupported format or encoding.\nDetails: \${details}'**
String attachmentDecodeError(String details);
/// Text shown when attachment could not be downloaded.
///
/// In en, this message translates to:
/// **'Unable to download this attachment.\nDetails: \${details}'**
String attachmentDownloadError(String details);
/// Action for single message.
///
/// In en, this message translates to:
/// **'Reply'**
String get messageActionReply;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Reply all'**
String get messageActionReplyAll;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Forward'**
String get messageActionForward;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Forward as attachment'**
String get messageActionForwardAsAttachment;
/// Action for single message to forward the given number of attachments.
///
/// In en, this message translates to:
/// **'{number,plural, =1{Forward attachment} other{Forward {number} attachments}}'**
String messageActionForwardAttachments(int number);
/// Action for multiple selected messages to forward all attachments of the messages.
///
/// In en, this message translates to:
/// **'Forward attachments'**
String get messagesActionForwardAttachments;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Delete'**
String get messageActionDelete;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Move to inbox'**
String get messageActionMoveToInbox;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Move'**
String get messageActionMove;
/// Status of single message.
///
/// In en, this message translates to:
/// **'Is read'**
String get messageStatusSeen;
/// Status of single message.
///
/// In en, this message translates to:
/// **'Is unread'**
String get messageStatusUnseen;
/// Status of single message.
///
/// In en, this message translates to:
/// **'Is flagged'**
String get messageStatusFlagged;
/// Status of single message.
///
/// In en, this message translates to:
/// **'Is not flagged'**
String get messageStatusUnflagged;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Mark as junk'**
String get messageActionMarkAsJunk;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Mark as not junk'**
String get messageActionMarkAsNotJunk;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Archive'**
String get messageActionArchive;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Move to Inbox'**
String get messageActionUnarchive;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Redirect'**
String get messageActionRedirect;
/// Action for single message.
///
/// In en, this message translates to:
/// **'Add notification'**
String get messageActionAddNotification;
/// Successful short snackbar message after deleting message(s).
///
/// In en, this message translates to:
/// **'Deleted'**
String get resultDeleted;
/// Successful short snackbar message after moving message(s) to junk.
///
/// In en, this message translates to:
/// **'Marked as junk'**
String get resultMovedToJunk;
/// Successful short snackbar message after moving message(s) to inbox.
///
/// In en, this message translates to:
/// **'Moved to Inbox'**
String get resultMovedToInbox;
/// Successful short snackbar message after moving message(s) to archive.
///
/// In en, this message translates to:
/// **'Archived'**
String get resultArchived;
/// Successful snackbar message after redirecting message to new recipient(s).
///
/// In en, this message translates to:
/// **'Message redirected 👍'**
String get resultRedirectedSuccess;
/// Failure snackbar message after failed to redirect message to new recipient(s).
///
/// In en, this message translates to:
/// **'Unable to redirect message.\n\nThe server responded with the following details: \"{details}\"'**
String resultRedirectedFailure(String details);
/// Title of redirect dialog.
///
/// In en, this message translates to:
/// **'Redirect'**
String get redirectTitle;
/// Short explanation of redirect action in redirect dialog.
///
/// In en, this message translates to:
/// **'Redirect this message to the following recipient(s). Redirecting does not alter the message.'**
String get redirectInfo;
/// Information when redirect is wanted but no address has been entered.
///
/// In en, this message translates to:
/// **'You need to add at least one valid email address.'**
String get redirectEmailInputRequired;
/// Description of search within the given folder.
///
/// In en, this message translates to:
/// **'Search in {folder}...'**
String searchQueryDescription(String folder);
/// Title for a search with the given query.
///
/// In en, this message translates to:
/// **'Search \"{query}\"'**
String searchQueryTitle(String query);
/// Legal info shown on initial welcome screen and later in about. [PP] is replaced with the legalesePrivacyPolicy text and [TC] with legaleseTermsAndConditions.
///
/// In en, this message translates to:
/// **'By using Maily you agree to our [PP] and to our [TC].'**
String get legaleseUsage;
/// Translation of privacy policy
///
/// In en, this message translates to:
/// **'Privacy Policy'**
String get legalesePrivacyPolicy;
/// Translation of Terms & Conditions
///
/// In en, this message translates to:
/// **'Terms & Conditions'**
String get legaleseTermsAndConditions;
/// Legal info shown in about dialog.
///
/// In en, this message translates to:
/// **'Maily is free software published under the GNU General Public License.'**
String get aboutApplicationLegalese;
/// Action to suggest a feature.
///
/// In en, this message translates to:
/// **'Suggest a feature'**
String get feedbackActionSuggestFeature;
/// Action to report a problem.
///
/// In en, this message translates to:
/// **'Report a problem'**
String get feedbackActionReportProblem;
/// Action to help developing.
///
/// In en, this message translates to:
/// **'Help developing Maily'**
String get feedbackActionHelpDeveloping;
/// Title of feedback settings screen.
///
/// In en, this message translates to:
/// **'Feedback'**
String get feedbackTitle;
/// Intro for feedback settings screen.
///
/// In en, this message translates to:
/// **'Thank you for testing Maily!'**
String get feedbackIntro;
/// Request to provide device and app information when reporting a problem.
///
/// In en, this message translates to:
/// **'Please provide this information when you report a problem:'**
String get feedbackProvideInfoRequest;
/// Info shown after copying device and app info to clipboard.
///
/// In en, this message translates to:
/// **'Copied to clipboard'**
String get feedbackResultInfoCopied;
/// Title of accounts settings screen.
///
/// In en, this message translates to:
/// **'Accounts'**
String get accountsTitle;
/// No description provided for @accountsActionReorder.
///
/// In en, this message translates to:
/// **'Reorder accounts'**
String get accountsActionReorder;
/// Title of base settings screen.
///
/// In en, this message translates to:
/// **'Settings'**
String get settingsTitle;
/// Settings option to block external options.
///
/// In en, this message translates to:
/// **'Block external images'**
String get settingsSecurityBlockExternalImages;
/// Title of dialog that shows additional information about the 'block external images' option.
///
/// In en, this message translates to:
/// **'External images'**
String get settingsSecurityBlockExternalImagesDescriptionTitle;
/// Text of dialog that shows additional information about the 'block external images' option.
///
/// In en, this message translates to:
/// **'Email messages can contain images that are either integrated or hosted on external servers. The latter, external images can expose information to the sender of the message, e.g. to let the sender know that you have opened the message. This option allows you to block such external images, which reduces the risk of exposing sensitive information. You can still opt in to load such images on a per-message-basis when you read a message.'**
String get settingsSecurityBlockExternalImagesDescriptionText;
/// Option for how to render messages.
///
/// In en, this message translates to:
/// **'Show full message contents'**
String get settingsSecurityMessageRenderingHtml;
/// Option for how to render messages.
///
/// In en, this message translates to:
/// **'Show only the text of messages'**
String get settingsSecurityMessageRenderingPlainText;
/// Option for how to launch URLs.
///
/// In en, this message translates to:
/// **'How should Maily open links?'**
String get settingsSecurityLaunchModeLabel;
/// Option for how to launch URLs.
///
/// In en, this message translates to:
/// **'Open links externally'**
String get settingsSecurityLaunchModeExternal;
/// Option for how to launch URLs.
///
/// In en, this message translates to:
/// **'Open links in Maily'**
String get settingsSecurityLaunchModeInApp;
/// Settings action to manage accounts.
///
/// In en, this message translates to:
/// **'Manage accounts'**
String get settingsActionAccounts;
/// Settings action to manage the visualization of the app.
///
/// In en, this message translates to:
/// **'Appearance'**
String get settingsActionDesign;
/// Settings action to provide feedback about the app.
///
/// In en, this message translates to:
/// **'Provide feedback'**
String get settingsActionFeedback;
/// Settings action to show welcome screen of the app again.
///
/// In en, this message translates to:
/// **'Show welcome'**
String get settingsActionWelcome;
/// Settings action to customize read receipts.
///
/// In en, this message translates to:
/// **'Read receipts'**
String get settingsReadReceipts;
/// Introduction text for managing read receipt requests.
///
/// In en, this message translates to:
/// **'Do you want to display read receipt requests?'**
String get readReceiptsSettingsIntroduction;
/// Display option for read receipt requests.
///
/// In en, this message translates to:
/// **'Always'**
String get readReceiptOptionAlways;
/// Display option for read receipt requests.
///
/// In en, this message translates to:
/// **'Never'**
String get readReceiptOptionNever;
/// Settings action to customize folders.
///
/// In en, this message translates to:
/// **'Folders'**
String get settingsFolders;
/// Introduction for folder names setting.
///
/// In en, this message translates to:
/// **'What names do you prefer for your folders?'**
String get folderNamesIntroduction;
/// Folder name setting option.
///
/// In en, this message translates to:
/// **'Names given by Maily'**
String get folderNamesSettingLocalized;
/// Folder name setting option.
///
/// In en, this message translates to:
/// **'Names given by the service'**
String get folderNamesSettingServer;
/// Folder name setting option.
///
/// In en, this message translates to:
/// **'My own custom names'**
String get folderNamesSettingCustom;
/// Action to specify custom folder names.
///
/// In en, this message translates to:
/// **'Edit custom names'**
String get folderNamesEditAction;
/// Title of dialog to specify custom folder names.
///
/// In en, this message translates to:
/// **'Custom names'**
String get folderNamesCustomTitle;
/// Action to create a new folder.
///
/// In en, this message translates to:
/// **'Create folder'**
String get folderAddAction;
/// Dialog title when creating a new folder.
///
/// In en, this message translates to:
/// **'Create folder'**
String get folderAddTitle;
/// Label for input field for the folder name.
///
/// In en, this message translates to:
/// **'Name'**
String get folderAddNameLabel;
/// Hint for input field for the folder name.
///
/// In en, this message translates to:
/// **'Name of the new folder'**
String get folderAddNameHint;
/// No description provided for @folderAccountLabel.
///
/// In en, this message translates to:
/// **'Account'**
String get folderAccountLabel;
/// No description provided for @folderMailboxLabel.
///
/// In en, this message translates to:
/// **'Folder'**
String get folderMailboxLabel;
/// Info for showing the creation success.
///
/// In en, this message translates to:
/// **'Folder created 😊'**
String get folderAddResultSuccess;
/// Info for showing a folder creation error.
///
/// In en, this message translates to:
/// **'Folder could not be created.\n\nThe server responded with {details}'**
String folderAddResultFailure(String details);
/// Action to delete an existing folder.
///
/// In en, this message translates to:
/// **'Delete'**
String get folderDeleteAction;
/// Dialog title to confirm deleting a folder.
///
/// In en, this message translates to:
/// **'Confirm'**
String get folderDeleteConfirmTitle;
/// Dialog text to confirm deleting a folder.
///
/// In en, this message translates to:
/// **'Do you really want to delete the folder {name}?'**
String folderDeleteConfirmText(String name);
/// Info for showing the creation success.
///
/// In en, this message translates to:
/// **'Folder deleted.'**
String get folderDeleteResultSuccess;
/// Info for showing a folder deletion error.
///
/// In en, this message translates to:
/// **'Folder could not be deleted.\n\nThe server responded with {details}'**
String folderDeleteResultFailure(String details);
/// Settings action to specify the development options.
///
/// In en, this message translates to:
/// **'Development settings'**
String get settingsDevelopment;
/// Title of the development mode section.
///
/// In en, this message translates to:
/// **'Development mode'**
String get developerModeTitle;
/// Text explaining the development mode.
///
/// In en, this message translates to:
/// **'If you enable the development mode you will be able to view the source code of messages and convert text attachments to messages.'**
String get developerModeIntroduction;
/// Text in checkbox to enable the development mode.
///
/// In en, this message translates to:
/// **'Enable development mode'**
String get developerModeEnable;
/// Action to convert text into an email.
///
/// In en, this message translates to:
/// **'Convert text to email'**
String get developerShowAsEmail;
/// Text shown when text cannot be converted into an email.
///
/// In en, this message translates to:
/// **'This text cannot be converted into a MIME message.'**
String get developerShowAsEmailFailed;
/// Title of design settings screen.
///
/// In en, this message translates to:
/// **'Design Settings'**
String get designTitle;
/// Title of theme section on design settings screen.
///
/// In en, this message translates to:
/// **'Theme'**
String get designSectionThemeTitle;
/// Theme option.
///
/// In en, this message translates to:
/// **'Light'**
String get designThemeOptionLight;
/// Theme option.
///
/// In en, this message translates to:
/// **'Dark'**
String get designThemeOptionDark;
/// Theme option.
///
/// In en, this message translates to:
/// **'System'**
String get designThemeOptionSystem;
/// Theme option.
///
/// In en, this message translates to:
/// **'Custom'**
String get designThemeOptionCustom;
/// Title of custom theme option section on design settings screen.
///
/// In en, this message translates to:
/// **'Enable dark theme'**
String get designSectionCustomTitle;
/// Start time of custom theme setting.
///
/// In en, this message translates to:
/// **'from {time}'**
String designThemeCustomStart(String time);
/// End time of custom theme setting.
///
/// In en, this message translates to:
/// **'until {time}'**
String designThemeCustomEnd(String time);
/// Title of color section on design settings screen.
///
/// In en, this message translates to:
/// **'Color Scheme'**
String get designSectionColorTitle;
/// Title of security settings screen.
///
/// In en, this message translates to:
/// **'Security'**
String get securitySettingsTitle;
/// Introduction of security settings screen.
///
/// In en, this message translates to:
/// **'Adapt the security settings to your personal needs.'**
String get securitySettingsIntro;
/// iOS-specific unlock reason.
///
/// In en, this message translates to:
/// **'Unlock Maily with Face ID.'**
String get securityUnlockWithFaceId;
/// iOS-specific unlock reason.
///
/// In en, this message translates to:
/// **'Unlock Maily with Touch ID.'**
String get securityUnlockWithTouchId;
/// Generic unlock reason.
///
/// In en, this message translates to:
/// **'Unlock Maily.'**
String get securityUnlockReason;
/// Generic unlock disable reason.
///
/// In en, this message translates to:
/// **'Unlock Maily to turn off lock.'**
String get securityUnlockDisableReason;
/// Message when biometric authentication is not available.
///
/// In en, this message translates to:
/// **'Your device does not support biometrics, possibly you need to set up unlock options first.'**
String get securityUnlockNotAvailable;
/// Label of biometric authentication lock feature.
///
/// In en, this message translates to:
/// **'Lock Maily'**
String get securityUnlockLabel;
/// Title to explain lock feature via biometric authentication.
///
/// In en, this message translates to:
/// **'Lock Maily'**
String get securityUnlockDescriptionTitle;
/// Text explaining lock feature via biometric authentication.
///
/// In en, this message translates to:
/// **'You can choose to lock access to Maily, so that others cannot read your email even when they have access to your device.'**
String get securityUnlockDescriptionText;
/// Lock timing option.
///
/// In en, this message translates to:
/// **'Lock immediately'**
String get securityLockImmediately;
/// Lock timing option.
///
/// In en, this message translates to:
/// **'Lock after 5 minutes'**
String get securityLockAfter5Minutes;
/// Lock timing option.
///
/// In en, this message translates to:
/// **'Lock after 30 minutes'**
String get securityLockAfter30Minutes;
/// Title of lock screen.
///
/// In en, this message translates to:
/// **'Maily is locked'**
String get lockScreenTitle;
/// Text on lock screen.
///
/// In en, this message translates to:
/// **'Maily is locked, please authenticate to proceed.'**
String get lockScreenIntro;
/// Action to unlock on lock screen.
///
/// In en, this message translates to:
/// **'Unlock'**
String get lockScreenUnlockAction;
/// Title of add account screen.
///
/// In en, this message translates to:
/// **'Add Account'**
String get addAccountTitle;
/// Label and section header of email address input field.
///
/// In en, this message translates to:
/// **'Email'**
String get addAccountEmailLabel;
/// Hint text of email address input field.
///
/// In en, this message translates to:
/// **'Please enter your email address'**
String get addAccountEmailHint;
/// Label shown while resolving the settings for the specified email address.
///
/// In en, this message translates to:
/// **'Resolving {email}...'**
String addAccountResolvingSettingsLabel(String email);
/// Button text shown for the user to edit server settings manually when the resolving was successful but turned out a different than expected provider name.
///
/// In en, this message translates to:
/// **'Not on {provider}?'**
String addAccountResolvedSettingsWrongAction(String provider);
/// Info shown after resolving the settings for the specified email address failed.
///
/// In en, this message translates to:
/// **'Unable to resolve {email}. Please go back to change it or set up the account manually.'**
String addAccountResolvingSettingsFailedInfo(String email);
/// Action shown after account settings could not be automatically be discovered.
///
/// In en, this message translates to:
/// **'Edit manually'**
String get addAccountEditManuallyAction;
/// Label and section header of password input field.
///
/// In en, this message translates to:
/// **'Password'**
String get addAccountPasswordLabel;
/// Hint text of password input field.
///
/// In en, this message translates to:
/// **'Please enter your password'**
String get addAccountPasswordHint;
/// Text shown when the provider of the email account requires app specific passwords to be set up.
///
/// In en, this message translates to:
/// **'This provider requires you to set up an app specific password.'**
String get addAccountApplicationPasswordRequiredInfo;
/// Button text for setting up app specific password.
///
/// In en, this message translates to:
/// **'Create app specific password'**
String get addAccountApplicationPasswordRequiredButton;
/// Acknowledgement to be confirmed by user to acknowledge the fact that an app specific password is required.
///
/// In en, this message translates to:
/// **'I already have an app password'**
String get addAccountApplicationPasswordRequiredAcknowledged;
/// Section header of verification/log in step.
///
/// In en, this message translates to:
/// **'Verification'**
String get addAccountVerificationStep;
/// Section header of account setup step.
///
/// In en, this message translates to:
/// **'Account Setup'**
String get addAccountSetupAccountStep;
/// Info shown while the account settings for the given email are verified.
///
/// In en, this message translates to:
/// **'Verifying {email}...'**
String addAccountVerifyingSettingsLabel(String email);
/// Info shown after the account settings for the given email have been verified.
///
/// In en, this message translates to:
/// **'Successfully signed into {email}.'**
String addAccountVerifyingSuccessInfo(String email);
/// Info shown after the account settings for the given email could not be verified.
///
/// In en, this message translates to:
/// **'Sorry, but there was a problem. Please check your email {email} and password.'**
String addAccountVerifyingFailedInfo(String email);
/// Info shown oauth process fails and the user can try again or use an app-specific password.
///
/// In en, this message translates to:
/// **'Sign in with {provider} or create an app-specific password.'**
String addAccountOauthOptionsText(String provider);
/// Label of button to sign in via oauth with the given provider.
///
/// In en, this message translates to:
/// **'Sign in with {provider}'**
String addAccountOauthSignIn(String provider);
/// Label of button to sign in via oauth with the Google.
///
/// In en, this message translates to:
/// **'Sign in with Google'**
String get addAccountOauthSignInGoogle;
/// Info to set up app specific password.
///
/// In en, this message translates to:
/// **'Alternatively, create an app password to sign in.'**
String get addAccountOauthSignInWithAppPassword;
/// Info shown when login fails for a provider that is know to require manual activation of IMAP access.
///
/// In en, this message translates to:
/// **'Your provider might require you to setup access for email apps manually.'**
String get accountAddImapAccessSetupMightBeRequired;
/// Label of button to launch website with instructions.
///
/// In en, this message translates to:
/// **'Setup email access'**
String get addAccountSetupImapAccessButtonLabel;
/// Label for user name input field.
///
/// In en, this message translates to:
/// **'Your name'**
String get addAccountNameOfUserLabel;
/// Hint for user name input field.
///
/// In en, this message translates to:
/// **'The name that recipients see'**
String get addAccountNameOfUserHint;
/// Label for account name input field.
///
/// In en, this message translates to:
/// **'Account name'**
String get addAccountNameOfAccountLabel;
/// Hint for account name input field.
///
/// In en, this message translates to:
/// **'Please enter the name of your account'**
String get addAccountNameOfAccountHint;
/// Title for screen when editing the account with the given name.
///
/// In en, this message translates to:
/// **'Edit {name}'**
String editAccountTitle(String name);
/// Info about not being able to connect to the named service. Most common causes are temporary network problems or a changed password.
///
/// In en, this message translates to:
/// **'Maily could not connect {name}.'**
String editAccountFailureToConnectInfo(String name);
/// Action to retry connecting to service again.
///
/// In en, this message translates to:
/// **'Retry'**
String get editAccountFailureToConnectRetryAction;
/// Action to change password for the service.
///
/// In en, this message translates to:
/// **'Change Password'**
String get editAccountFailureToConnectChangePasswordAction;
/// Title of dialog shown after successfully connecting a failed account again.
///
/// In en, this message translates to:
/// **'Connected'**
String get editAccountFailureToConnectFixedTitle;
/// Message of dialog shown after successfully connecting a failed account again.
///
/// In en, this message translates to:
/// **'The account is connected again.'**
String get editAccountFailureToConnectFixedInfo;
/// Label for opting this account in/out of the unified account.
///
/// In en, this message translates to:
/// **'Include in unified account'**
String get editAccountIncludeInUnifiedLabel;
/// Label for any alias addresses that have been specified for the given email address.
///
/// In en, this message translates to:
/// **'Alias email addresses for {email}:'**
String editAccountAliasLabel(String email);
/// Info when there have been no aliases specified for this account.
///
/// In en, this message translates to:
/// **'You have no known aliases for this account yet.'**
String get editAccountNoAliasesInfo;
/// Info given after an alias was removed.
///
/// In en, this message translates to:
/// **'{email} alias removed'**
String editAccountAliasRemoved(String email);
/// Button text for adding an alias to this account.
///
/// In en, this message translates to:
/// **'Add alias'**
String get editAccountAddAliasAction;
/// Info shown when + aliases are supported by this account.
///
/// In en, this message translates to:
/// **'Supports + aliases'**
String get editAccountPlusAliasesSupported;
/// Button text for testing of + aliases are supported by this account.
///
/// In en, this message translates to:
/// **'Test support for + aliases'**
String get editAccountCheckPlusAliasAction;
/// Label of checkbox to enable the BCC-MYSELF-Feature.
///
/// In en, this message translates to:
/// **'BCC myself'**
String get editAccountBccMyself;
/// Title of alert explaining the BCC-MYSELF-Feature.
///
/// In en, this message translates to:
/// **'BCC myself'**
String get editAccountBccMyselfDescriptionTitle;
/// Explanation of the the BCC-MYSELF-Feature.
///
/// In en, this message translates to:
/// **'You can automatically send messages to yourself for every message you send from this account with the \"BCC myself\" feature. Usually this is not required and wanted as all outgoing messages are stored in the \"Sent\" folder anyhow.'**
String get editAccountBccMyselfDescriptionText;
/// Button text for editing the server settings of this account.
///
/// In en, this message translates to:
/// **'Edit server settings'**
String get editAccountServerSettingsAction;
/// Button text for deleting this account.
///
/// In en, this message translates to:
/// **'Delete account'**
String get editAccountDeleteAccountAction;
/// Title for confirmation dialog when deleting this account.
///
/// In en, this message translates to:
/// **'Confirm'**
String get editAccountDeleteAccountConfirmationTitle;
/// Request to confirm when deleting this account.
///
/// In en, this message translates to:
/// **'Do you want to delete the account {name}?'**
String editAccountDeleteAccountConfirmationQuery(String name);
/// Title for dialog shown while testing + alias support
///
/// In en, this message translates to:
/// **'+ Aliases for {name}'**
String editAccountTestPlusAliasTitle(String name);
/// Title for introducing concept of + aliases.
///
/// In en, this message translates to:
/// **'Introduction'**
String get editAccountTestPlusAliasStepIntroductionTitle;
/// Text for introducing concept of + aliases.
///
/// In en, this message translates to:
/// **'Your account {accountName} might support so called + aliases like {example}.\nA + alias helps you to protect your identity and helps you against spam.\nTo test this, a test message will be sent to this generated address. If it arrives, your provider supports + aliases and you can easily generate them on demand when writing a new mail message.'**
String editAccountTestPlusAliasStepIntroductionText(String accountName, String example);
/// Title while testing concept of + aliases.
///
/// In en, this message translates to:
/// **'Testing'**
String get editAccountTestPlusAliasStepTestingTitle;
/// Title after testing concept of + aliases.
///
/// In en, this message translates to:
/// **'Result'**
String get editAccountTestPlusAliasStepResultTitle;
/// Result when account supports + aliases
///
/// In en, this message translates to:
/// **'Your account {name} supports + aliases.'**
String editAccountTestPlusAliasStepResultSuccess(String name);
/// Result when account does not supports + aliases
///
/// In en, this message translates to:
/// **'Your account {name} does not support + aliases.'**
String editAccountTestPlusAliasStepResultNoSuccess(String name);
/// Title when adding new alias.
///
/// In en, this message translates to:
/// **'Add alias'**
String get editAccountAddAliasTitle;
/// Title when editing alias.
///
/// In en, this message translates to:
/// **'Edit alias'**
String get editAccountEditAliasTitle;
/// Action when adding new alias.
///
/// In en, this message translates to:
/// **'Add'**
String get editAccountAliasAddAction;
/// Action when editing alias.
///
/// In en, this message translates to:
/// **'Update'**
String get editAccountAliasUpdateAction;
/// Label for alias name input field.
///
/// In en, this message translates to:
/// **'Alias name'**
String get editAccountEditAliasNameLabel;
/// Label for alias email input field.
///
/// In en, this message translates to:
/// **'Alias email'**
String get editAccountEditAliasEmailLabel;
/// Hint for alias email input field.
///
/// In en, this message translates to:
/// **'Your alias email address'**
String get editAccountEditAliasEmailHint;
/// Error when the alias email is already known
///
/// In en, this message translates to:
/// **'There is already an alias with {email}.'**
String editAccountEditAliasDuplicateError(String email);
/// Label developer mode option to enable logging.
///
/// In en, this message translates to:
/// **'Enable logging'**
String get editAccountEnableLogging;
/// Short message shown after the log has been enabled.
///
/// In en, this message translates to:
/// **'Log enabled, please restart'**
String get editAccountLoggingEnabled;
/// Short message shown after the log has been disabled.
///
/// In en, this message translates to:
/// **'Log disabled, please restart'**
String get editAccountLoggingDisabled;
/// Title shown when account name is not set.
///
/// In en, this message translates to:
/// **'Server Settings'**
String get accountDetailsFallbackTitle;
/// Title for error dialogs.
///
/// In en, this message translates to:
/// **'Error'**
String get errorTitle;
/// Step to select a provider.
///
/// In en, this message translates to:
/// **'Email Service Provider'**
String get accountProviderStepTitle;
/// When no standard provider is chosen.
///
/// In en, this message translates to:
/// **'Other email service'**
String get accountProviderCustom;
/// Error details when no connection to server could be established at all
///
/// In en, this message translates to:
/// **'Maily cannot reach the specified mail server. Please check your incoming server setting \"{incomingHost}\" and your outgoing server setting \"{outgoingHost}\".'**
String accountDetailsErrorHostProblem(String incomingHost, String outgoingHost);
/// Error details when login fails
///
/// In en, this message translates to:
/// **'Unable to log your in. Please check your user name \"{userName}\" and your password \"{password}\".'**
String accountDetailsErrorLoginProblem(String userName, String password);
/// Label for user name input field.
///
/// In en, this message translates to:
/// **'Login name'**
String get accountDetailsUserNameLabel;
/// Hint for user name input field.
///
/// In en, this message translates to:
/// **'Your user name, if different from email'**
String get accountDetailsUserNameHint;
/// Label for password input field.
///
/// In en, this message translates to:
/// **'Login password'**
String get accountDetailsPasswordLabel;
/// Hint for user password input field.
///
/// In en, this message translates to:
/// **'Your password'**
String get accountDetailsPasswordHint;
/// Title of base settings section.
///
/// In en, this message translates to:
/// **'Base settings'**
String get accountDetailsBaseSectionTitle;
/// Label for incoming server domain field.
///
/// In en, this message translates to:
/// **'Incoming server'**
String get accountDetailsIncomingLabel;
/// Hint for incoming server domain field.
///
/// In en, this message translates to:
/// **'Domain like imap.domain.com'**
String get accountDetailsIncomingHint;
/// Label for outgoing server domain field.
///
/// In en, this message translates to:
/// **'Outgoing server'**
String get accountDetailsOutgoingLabel;
/// Hint for outgoing server domain field.
///
/// In en, this message translates to:
/// **'Domain like smtp.domain.com'**
String get accountDetailsOutgoingHint;
/// Title of incoming settings section.
///
/// In en, this message translates to:
/// **'Advanced incoming settings'**
String get accountDetailsAdvancedIncomingSectionTitle;
/// Label for server type dropdown.
///
/// In en, this message translates to:
/// **'Incoming type:'**
String get accountDetailsIncomingServerTypeLabel;
/// Option when the server type/security should be discovered automatically.
///
/// In en, this message translates to:
/// **'automatic'**
String get accountDetailsOptionAutomatic;
/// Label for server security dropdown.
///
/// In en, this message translates to:
/// **'Incoming security:'**
String get accountDetailsIncomingSecurityLabel;
/// Label for security dropdown option without encryption.
///
/// In en, this message translates to:
/// **'Plain (no encryption)'**
String get accountDetailsSecurityOptionNone;
/// Label for incoming port input field.
///
/// In en, this message translates to:
/// **'Incoming port'**
String get accountDetailsIncomingPortLabel;
/// Hint for port input fields.
///
/// In en, this message translates to:
/// **'Leave empty to determine automatically'**
String get accountDetailsPortHint;
/// Label for incoming user name input field.
///
/// In en, this message translates to:
/// **'Incoming user name'**
String get accountDetailsIncomingUserNameLabel;
/// Label for alternative user name input fields.
///
/// In en, this message translates to:
/// **'Your user name, if different from above'**
String get accountDetailsAlternativeUserNameHint;
/// Label for incoming password input field.
///
/// In en, this message translates to:
/// **'Incoming password'**
String get accountDetailsIncomingPasswordLabel;
/// Label for alternative user name input fields.
///
/// In en, this message translates to:
/// **'Your password, if different from above'**
String get accountDetailsAlternativePasswordHint;
/// Title of incoming settings section.
///
/// In en, this message translates to:
/// **'Advanced outgoing settings'**
String get accountDetailsAdvancedOutgoingSectionTitle;
/// Label for server type dropdown.
///
/// In en, this message translates to:
/// **'Outgoing type:'**
String get accountDetailsOutgoingServerTypeLabel;
/// Label for server security dropdown.
///
/// In en, this message translates to:
/// **'Outgoing security:'**
String get accountDetailsOutgoingSecurityLabel;
/// Label for outgoing port input field.
///
/// In en, this message translates to:
/// **'Outgoing port'**
String get accountDetailsOutgoingPortLabel;
/// Label for outgoing user name input field.
///
/// In en, this message translates to:
/// **'Outgoing user name'**
String get accountDetailsOutgoingUserNameLabel;
/// Label for outgoing password input field.
///
/// In en, this message translates to:
/// **'Outgoing password'**
String get accountDetailsOutgoingPasswordLabel;
/// Title for compose screen when a new message is created.
///
/// In en, this message translates to:
/// **'New message'**
String get composeTitleNew;
/// Title for compose screen when a message is forwarded.
///
/// In en, this message translates to:
/// **'Forward'**
String get composeTitleForward;
/// Title for compose screen when a message is replied.
///
/// In en, this message translates to:
/// **'Reply'**
String get composeTitleReply;
/// Message text for message without text.
///
/// In en, this message translates to:
/// **'empty message'**
String get composeEmptyMessage;
/// Warning shown when trying to send a message without subject.
///
/// In en, this message translates to:
/// **'You have not specified a subject. Do you want to sent the message without a subject?'**
String get composeWarningNoSubject;
/// Action to send message without subject.
///
/// In en, this message translates to:
/// **'Send'**
String get composeActionSentWithoutSubject;
/// Notification shown after a mail was sent successfully.
///
/// In en, this message translates to:
/// **'Mail sent 😊'**
String get composeMailSendSuccess;
/// Error shown when email could not be send
///
/// In en, this message translates to:
/// **'Sorry, your mail could not be send. We received the following error:\n{details}.'**
String composeSendErrorInfo(String details);
/// Action to request a read receipt for this message
///
/// In en, this message translates to:
/// **'Request read receipt'**
String get composeRequestReadReceiptAction;
/// Action to save a message as draft
///
/// In en, this message translates to:
/// **'Save as draft'**
String get composeSaveDraftAction;
/// Info shown when message was saved as draft successfully
///
/// In en, this message translates to:
/// **'Draft saved'**
String get composeMessageSavedAsDraft;
/// Info shown when message could not be saved as a draft
///
/// In en, this message translates to:
/// **'Your draft could not be saved with the following error:\n{details}'**
String composeMessageSavedAsDraftErrorInfo(String details);
/// Action to write a plain text message instead of an html message
///
/// In en, this message translates to:
/// **'Convert to plain text'**
String get composeConvertToPlainTextEditorAction;
/// Action to write a HTML message instead of a text message
///
/// In en, this message translates to:
/// **'Convert to rich message (HTML)'**
String get composeConvertToHtmlEditorAction;
/// Action to return to compose screen when draft cannot be saved
///
/// In en, this message translates to:
/// **'Continue editing'**
String get composeContinueEditingAction;
/// Action to create a new + alias as a sender
///
/// In en, this message translates to:
/// **'Create new + alias...'**
String get composeCreatePlusAliasAction;
/// Hint for From input field
///
/// In en, this message translates to:
/// **'Sender'**
String get composeSenderHint;
/// Hint for To input field
///
/// In en, this message translates to:
/// **'Recipient email'**
String get composeRecipientHint;
/// Label for Subject input field
///
/// In en, this message translates to:
/// **'Subject'**
String get composeSubjectLabel;
/// Hint for Subject input field
///
/// In en, this message translates to:
/// **'Message subject'**
String get composeSubjectHint;
/// Action to add an attachment - should be short!
///
/// In en, this message translates to:
/// **'Add'**
String get composeAddAttachmentAction;
/// Action to remove an attachment
///
/// In en, this message translates to:
/// **'Remove {name}'**
String composeRemoveAttachmentAction(String name);
/// Info shown after leaving compose screen to allow an easy return
///
/// In en, this message translates to:
/// **'Left by mistake?'**
String get composeLeftByMistake;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'File'**
String get attachTypeFile;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'Photo'**
String get attachTypePhoto;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'Video'**
String get attachTypeVideo;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'Audio'**
String get attachTypeAudio;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'Location'**
String get attachTypeLocation;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'Animated Gif'**
String get attachTypeGif;
/// Text for searching in GIPHY service for GIF
///
/// In en, this message translates to:
/// **'search GIPHY'**
String get attachTypeGifSearch;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'Sticker'**
String get attachTypeSticker;
/// Text for searching in GIPHY service for sticker
///
/// In en, this message translates to:
/// **'search GIPHY'**
String get attachTypeStickerSearch;
/// Attachment type to add
///
/// In en, this message translates to:
/// **'Appointment'**
String get attachTypeAppointment;
/// Title of language setting screen
///
/// In en, this message translates to:
/// **'Language'**
String get languageSettingTitle;
/// Label for language setting dropdown screen
///
/// In en, this message translates to:
/// **'Choose the language for Maily:'**
String get languageSettingLabel;
/// Option to use the system's settings
///
/// In en, this message translates to:
/// **'System language'**
String get languageSettingSystemOption;
/// Title of dialog to confirm when switching the language
///
/// In en, this message translates to:
/// **'Use English for Maily?'**
String get languageSettingConfirmationTitle;
/// Query to be confirmed by user when switching the language
///
/// In en, this message translates to:
/// **'Please confirm to use English as your chosen language.'**
String get languageSettingConfirmationQuery;
/// Info text after having specified the language.
///
/// In en, this message translates to:
/// **'Maily is now shown in English.'**
String get languageSetInfo;
/// Info text after choosing the system's language for Maily.
///
/// In en, this message translates to:
/// **'Maily will now use the system\'s language or English if the system\'s language is not supported.'**
String get languageSystemSetInfo;
/// Title of swipe setting screen
///
/// In en, this message translates to:
/// **'Swipe gestures'**
String get swipeSettingTitle;
/// Label for swipe gesture
///
/// In en, this message translates to:
/// **'Left to right swipe'**
String get swipeSettingLeftToRightLabel;
/// Label for swipe gesture
///
/// In en, this message translates to:
/// **'Right to left swipe'**
String get swipeSettingRightToLeftLabel;
/// Action for changing a swipe gesture
///
/// In en, this message translates to:
/// **'Change'**
String get swipeSettingChangeAction;
/// Title of signature setting screen
///
/// In en, this message translates to:
/// **'Signature'**
String get signatureSettingsTitle;
/// Text before selecting message types for a signature (new, forward, reply).
///
/// In en, this message translates to:
/// **'Enable the signature for the following messages:'**
String get signatureSettingsComposeActionsInfo;
/// Informational text before showing link to account settings.
///
/// In en, this message translates to:
/// **'You can specify account specific signatures in the account settings.'**
String get signatureSettingsAccountInfo;
/// Action to add account specific signature.
///
/// In en, this message translates to:
/// **'Add signature for {account}'**
String signatureSettingsAddForAccount(String account);
/// Title of default sender setting screen
///
/// In en, this message translates to:
/// **'Default sender'**
String get defaultSenderSettingsTitle;
/// Description of default sender setting screen
///
/// In en, this message translates to:
/// **'Select the sender for new messages.'**
String get defaultSenderSettingsLabel;
/// The default sender is the one from the first account
///
/// In en, this message translates to:
/// **'First account ({email})'**
String defaultSenderSettingsFirstAccount(String email);
/// Info about that email aliases can be set up in the account settings. [AS] is the place, where defaultSenderSettingsAliasAccountSettings is included as a link.
///
/// In en, this message translates to:
/// **'You can set up email alias addresses in the [AS].'**
String get defaultSenderSettingsAliasInfo;
/// Text of the account settings link.
///
/// In en, this message translates to:
/// **'account settings'**
String get defaultSenderSettingsAliasAccountSettings;
/// Reply settings title.
///
/// In en, this message translates to:
/// **'Message format'**
String get replySettingsTitle;
/// Reply settings introduction text.
///
/// In en, this message translates to:
/// **'In what format do you want to answer or forward email by default?'**
String get replySettingsIntro;
/// Reply settings option.
///
/// In en, this message translates to:
/// **'Always rich format (HTML)'**
String get replySettingsFormatHtml;
/// Reply settings option.
///
/// In en, this message translates to:
/// **'Use same format as originating email'**
String get replySettingsFormatSameAsOriginal;
/// Reply settings option.
///
/// In en, this message translates to:
/// **'Always text-only'**
String get replySettingsFormatPlainText;
/// Title of move to mailbox dialog.
///
/// In en, this message translates to:
/// **'Move message'**
String get moveTitle;
/// Message after moving message successfully.
///
/// In en, this message translates to:
/// **'Messaged moved to {mailbox}.'**
String moveSuccess(String mailbox);
/// Label of input field when inserting a formatted text
///
/// In en, this message translates to:
/// **'Your input'**
String get editorArtInputLabel;
/// Hint of input field when inserting a formatted text
///
/// In en, this message translates to:
/// **'Enter text here'**
String get editorArtInputHint;
/// Text shown while waiting for input
///
/// In en, this message translates to:
/// **'waiting for input...'**
String get editorArtWaitingForInputHint;
/// Font name
///
/// In en, this message translates to:
/// **'Serif bold'**
String get fontSerifBold;
/// Font name
///
/// In en, this message translates to:
/// **'Serif italic'**
String get fontSerifItalic;
/// Font name
///
/// In en, this message translates to:
/// **'Serif bold italic'**
String get fontSerifBoldItalic;
/// Font name
///
/// In en, this message translates to:
/// **'Sans'**
String get fontSans;
/// Font name
///
/// In en, this message translates to:
/// **'Sans bold'**
String get fontSansBold;
/// Font name
///
/// In en, this message translates to:
/// **'Sans italic'**
String get fontSansItalic;
/// Font name
///
/// In en, this message translates to:
/// **'Sans bold italic'**
String get fontSansBoldItalic;
/// Font name
///
/// In en, this message translates to:
/// **'Script'**
String get fontScript;
/// Font name
///
/// In en, this message translates to:
/// **'Script bold'**
String get fontScriptBold;
/// Font name
///
/// In en, this message translates to:
/// **'Fraktur'**
String get fontFraktur;
/// Font name
///
/// In en, this message translates to:
/// **'Fraktur bold'**
String get fontFrakturBold;
/// Font name
///
/// In en, this message translates to:
/// **'Monospace'**
String get fontMonospace;
/// Font name
///
/// In en, this message translates to:
/// **'Fullwidth'**
String get fontFullwidth;
/// Font name
///
/// In en, this message translates to:
/// **'Double struck'**
String get fontDoublestruck;
/// Font name
///
/// In en, this message translates to:
/// **'Capitalized'**
String get fontCapitalized;
/// Font name
///
/// In en, this message translates to:
/// **'Circled'**
String get fontCircled;
/// Font name
///
/// In en, this message translates to:
/// **'Parenthesized'**
String get fontParenthesized;
/// Font name
///
/// In en, this message translates to:
/// **'Underlined'**
String get fontUnderlinedSingle;
/// Font name
///
/// In en, this message translates to:
/// **'Underlined double'**
String get fontUnderlinedDouble;
/// Font name
///
/// In en, this message translates to:
/// **'Strike through'**
String get fontStrikethroughSingle;
/// Font name
///
/// In en, this message translates to:
/// **'Crosshatch'**
String get fontCrosshatch;
/// Message shown when single account could not be loaded.
///
/// In en, this message translates to:
/// **'Unable to connect to your account {name}. Has the password been changed?'**
String accountLoadError(String name);
/// Action to edit account
///
/// In en, this message translates to:
/// **'Edit account'**
String get accountLoadErrorEditAction;
/// Title of extension section within the development settings
///
/// In en, this message translates to:
/// **'Extensions'**
String get extensionsTitle;
/// Explanation of extensions
///
/// In en, this message translates to:
/// **'With extensions e-mail service providers, companies and developers can adapt Maily with useful functionalities.'**
String get extensionsIntro;
/// Label for launching a website with more information
///
/// In en, this message translates to:
/// **'Learn more about extensions'**
String get extensionsLearnMoreAction;
/// Action to refresh extensions
///
/// In en, this message translates to:
/// **'Reload extensions'**
String get extensionsReloadAction;
/// Action to deactivate / unload any extension
///
/// In en, this message translates to:
/// **'Deactivate all extensions'**
String get extensionDeactivateAllAction;
/// Action to load extension manually
///
/// In en, this message translates to:
/// **'Load manually'**
String get extensionsManualAction;
/// Label for URL input field
///
/// In en, this message translates to:
/// **'Url of extension'**
String get extensionsManualUrlLabel;
/// Message shown when extensions could not be loaded.
///
/// In en, this message translates to:
/// **'Unable to download extension from \"{url}\".'**
String extensionsManualLoadingError(String url);
/// Action to accept an icalendar invitation tentatively
///
/// In en, this message translates to:
/// **'Tentatively'**
String get icalendarAcceptTentatively;
/// Action to change an icalendar invitation participant status
///
/// In en, this message translates to:
/// **'Change'**
String get icalendarActionChangeParticipantStatus;
/// Label of the summary info of an icalendar object
///
/// In en, this message translates to:
/// **'Title'**
String get icalendarLabelSummary;
/// Info shown when the icalendar object has no summary (no title)
///
/// In en, this message translates to:
/// **'(no title)'**
String get icalendarNoSummaryInfo;
/// Label of the description info of an icalendar object
///
/// In en, this message translates to:
/// **'Description'**
String get icalendarLabelDescription;
/// Label of the start datetime info of an icalendar object
///
/// In en, this message translates to:
/// **'Start'**
String get icalendarLabelStart;
/// Label of the end datetime info of an icalendar object
///
/// In en, this message translates to:
/// **'End'**
String get icalendarLabelEnd;
/// Label of the duration info of an icalendar object
///
/// In en, this message translates to:
/// **'Duration'**
String get icalendarLabelDuration;
/// Label of the location info of an icalendar object
///
/// In en, this message translates to:
/// **'Location'**
String get icalendarLabelLocation;
/// Label of the ms teams url info of an icalendar object
///
/// In en, this message translates to:
/// **'Link'**
String get icalendarLabelTeamsUrl;
/// Label of the recurrence info of an icalendar object
///
/// In en, this message translates to:
/// **'Repeats'**
String get icalendarLabelRecurrenceRule;
/// Label of the participants info of an icalendar object
///
/// In en, this message translates to:
/// **'Participants'**
String get icalendarLabelParticipants;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'You are asked to answer this invitation.'**
String get icalendarParticipantStatusNeedsAction;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'You have accepted this invitation.'**
String get icalendarParticipantStatusAccepted;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'You have declined this invitation.'**
String get icalendarParticipantStatusDeclined;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'You have tentatively accepted this invitation.'**
String get icalendarParticipantStatusAcceptedTentatively;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'You have delegated this invitation.'**
String get icalendarParticipantStatusDelegated;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'The task is in progress.'**
String get icalendarParticipantStatusInProcess;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'The task is partially done.'**
String get icalendarParticipantStatusPartial;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'The task is done.'**
String get icalendarParticipantStatusCompleted;
/// Participant status of the current user for a icalendar object
///
/// In en, this message translates to:
/// **'Your status is unknown.'**
String get icalendarParticipantStatusOther;
/// Title for dialog to change participant status
///
/// In en, this message translates to:
/// **'Your Status'**
String get icalendarParticipantStatusChangeTitle;
/// Text of dialog to change participant status
///
/// In en, this message translates to:
/// **'Do you want to accept this invitation?'**
String get icalendarParticipantStatusChangeText;
/// Failure message for a status change reply
///
/// In en, this message translates to:
/// **'Unable to send reply.\nThe server responded with the following details:\n{details}'**
String icalendarParticipantStatusSentFailure(String details);
/// Action to export the invite to the native calendar
///
/// In en, this message translates to:
/// **'Export'**
String get icalendarExportAction;
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has not answered this invitation.'**
String icalendarReplyStatusNeedsAction(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has accepted the appointment.'**
String icalendarReplyStatusAccepted(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has declined this invitation.'**
String icalendarReplyStatusDeclined(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has tentatively accepted this invitation.'**
String icalendarReplyStatusAcceptedTentatively(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has delegated this invitation.'**
String icalendarReplyStatusDelegated(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has started this task.'**
String icalendarReplyStatusInProcess(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has partially done this task.'**
String icalendarReplyStatusPartial(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has finished this task.'**
String icalendarReplyStatusCompleted(String attendee);
/// Valid Calendar reply
///
/// In en, this message translates to:
/// **'{attendee} has answered with an unknown status.'**
String icalendarReplyStatusOther(String attendee);
/// Calendar reply without any participant
///
/// In en, this message translates to:
/// **'This calendar reply contains no participants.'**
String get icalendarReplyWithoutParticipants;
/// Calendar reply without any participant status
///
/// In en, this message translates to:
/// **'{attendee} replied without an participation status.'**
String icalendarReplyWithoutStatus(String attendee);
/// Title for adding a new appointment screen
///
/// In en, this message translates to:
/// **'Create Appointment'**
String get composeAppointmentTitle;
/// Label for select day button
///
/// In en, this message translates to:
/// **'day'**
String get composeAppointmentLabelDay;
/// Label for select time button
///
/// In en, this message translates to:
/// **'time'**
String get composeAppointmentLabelTime;
/// Label for is all day toggle
///
/// In en, this message translates to:
/// **'All day'**
String get composeAppointmentLabelAllDayEvent;
/// Label for repeat drop-down
///
/// In en, this message translates to:
/// **'Repeat'**
String get composeAppointmentLabelRepeat;
/// Option for repeat drop-down
///
/// In en, this message translates to:
/// **'Never'**
String get composeAppointmentLabelRepeatOptionNever;
/// Option for repeat drop-down
///
/// In en, this message translates to:
/// **'Daily'**
String get composeAppointmentLabelRepeatOptionDaily;
/// Option for repeat drop-down
///
/// In en, this message translates to:
/// **'Weekly'**
String get composeAppointmentLabelRepeatOptionWeekly;
/// Option for repeat drop-down
///
/// In en, this message translates to:
/// **'Monthly'**
String get composeAppointmentLabelRepeatOptionMonthly;
/// Option for repeat drop-down
///
/// In en, this message translates to:
/// **'Annually'**
String get composeAppointmentLabelRepeatOptionYearly;
/// Label for frequency drop-down
///
/// In en, this message translates to:
/// **'Frequency'**
String get composeAppointmentRecurrenceFrequencyLabel;
/// Label for interval drop-down
///
/// In en, this message translates to:
/// **'Interval'**
String get composeAppointmentRecurrenceIntervalLabel;
/// Label for days selection area in a weekly or monthly recurrence
///
/// In en, this message translates to:
/// **'On days'**
String get composeAppointmentRecurrenceDaysLabel;
/// Label for choosing end date of recurrence
///
/// In en, this message translates to:
/// **'Until'**
String get composeAppointmentRecurrenceUntilLabel;
/// Option for no end date of recurrence
///
/// In en, this message translates to:
/// **'Unlimited'**
String get composeAppointmentRecurrenceUntilOptionUnlimited;
/// Option for standard end date of recurrence with the given duration
///
/// In en, this message translates to:
/// **'Recommended ({duration})'**
String composeAppointmentRecurrenceUntilOptionRecommended(String duration);
/// Option for specific end date of recurrence
///
/// In en, this message translates to:
/// **'Until chosen date'**
String get composeAppointmentRecurrenceUntilOptionSpecificDate;
/// Option for repeating an event always on that day of the month
///
/// In en, this message translates to:
/// **'On the {day}. day of the month'**
String composeAppointmentRecurrenceMonthlyOnDayOfMonth(int day);
/// Monthly repeat on weekday of a chosen week
///
/// In en, this message translates to:
/// **'Weekday in month'**
String get composeAppointmentRecurrenceMonthlyOnWeekDay;
/// Monthly day option
///
/// In en, this message translates to:
/// **'First'**
String get composeAppointmentRecurrenceFirst;
/// Monthly day option
///
/// In en, this message translates to:
/// **'Second'**
String get composeAppointmentRecurrenceSecond;
/// Monthly day option
///
/// In en, this message translates to:
/// **'Third'**
String get composeAppointmentRecurrenceThird;
/// Monthly day option
///
/// In en, this message translates to:
/// **'Last'**
String get composeAppointmentRecurrenceLast;
/// Monthly day option
///
/// In en, this message translates to:
/// **'Second-last'**
String get composeAppointmentRecurrenceSecondLast;
/// Duration. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{1 year} other{{number} years}}'**
String durationYears(int number);
/// Duration. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{1 month} other{{number} months}}'**
String durationMonths(int number);
/// Duration. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{1 week} other{{number} weeks}}'**
String durationWeeks(int number);
/// Duration. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{1 day} other{{number} days}}'**
String durationDays(int number);
/// Duration. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{1 hour} other{{number} hours}}'**
String durationHours(int number);
/// Duration. Message formatted using the plural JSON scheme.
///
/// In en, this message translates to:
/// **'{number,plural, =1{1 minute} other{{number} minutes}}'**
String durationMinutes(int number);
/// Text shown when the duration is 0
///
/// In en, this message translates to:
/// **'No duration'**
String get durationEmpty;
}
class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const _AppLocalizationsDelegate();
@override
Future<AppLocalizations> load(Locale locale) {
return SynchronousFuture<AppLocalizations>(lookupAppLocalizations(locale));
}
@override
bool isSupported(Locale locale) => <String>['de', 'en', 'es'].contains(locale.languageCode);
@override
bool shouldReload(_AppLocalizationsDelegate old) => false;
}
AppLocalizations lookupAppLocalizations(Locale locale) {
// Lookup logic when only language code is specified.
switch (locale.languageCode) {
case 'de': return AppLocalizationsDe();
case 'en': return AppLocalizationsEn();
case 'es': return AppLocalizationsEs();
}
throw FlutterError(
'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely '
'an issue with the localizations generation tool. Please file an issue '
'on GitHub with a reproducible sample app and the gen-l10n configuration '
'that was used.'
);
}
| 0
|
mirrored_repositories/enough_mail_app/lib/src
|
mirrored_repositories/enough_mail_app/lib/src/localization/app_localizations_es.g.dart
|
import 'package:intl/intl.dart' as intl;
import 'app_localizations.g.dart';
/// The translations for Spanish Castilian (`es`).
class AppLocalizationsEs extends AppLocalizations {
AppLocalizationsEs([String locale = 'es']) : super(locale);
@override
String get signature => 'Enviado con Maily';
@override
String get actionCancel => 'Cancelar';
@override
String get actionOk => 'Ok';
@override
String get actionDone => 'Hecho';
@override
String get actionNext => 'Siguiente';
@override
String get actionSkip => 'Saltar';
@override
String get actionUndo => 'Deshacer';
@override
String get actionDelete => 'Eliminar';
@override
String get actionAccept => 'Aceptar';
@override
String get actionDecline => 'Rechazar';
@override
String get actionEdit => 'Editar';
@override
String get actionAddressCopy => 'Copiar';
@override
String get actionAddressCompose => 'Nuevo mensaje';
@override
String get actionAddressSearch => 'Buscar';
@override
String get splashLoading1 => 'Iniciando...';
@override
String get splashLoading2 => 'Preparando tu Motor de Maily...';
@override
String get splashLoading3 => 'Lanzando en el 10, 9, 8...';
@override
String get welcomePanel1Title => 'Maily';
@override
String get welcomePanel1Text => 'Bienvenido a Maily, tu ayudante de correo electrónico rápido y amistoso!';
@override
String get welcomePanel2Title => 'Cuentas';
@override
String get welcomePanel2Text => 'Administra cuentas de correo electrónico ilimitadas. Lee y busca correos en todas tus cuentas a la vez.';
@override
String get welcomePanel3Title => 'Deslizar y pulsar largo';
@override
String get welcomePanel3Text => 'Desliza el dedo por tus mensajes para borrarlos o marcarlos como leídos. Mantén pulsado un mensaje para seleccionarlo y gestionar varios.';
@override
String get welcomePanel4Title => 'Mantén tu bandeja de entrada limpia';
@override
String get welcomePanel4Text => 'Darse de baja de los boletines con un solo toque.';
@override
String get welcomeActionSignIn => 'Inicia sesión en tu cuenta de correo';
@override
String get homeSearchHint => 'Tu búsqueda';
@override
String get homeActionsShowAsStack => 'Mostrar como pila';
@override
String get homeActionsShowAsList => 'Mostrar como lista';
@override
String get homeEmptyFolderMessage => '¡Todo listo!\n\nNo hay mensajes en esta carpeta.';
@override
String get homeEmptySearchMessage => 'No se encontraron mensajes.';
@override
String get homeDeleteAllTitle => 'Confirmar';
@override
String get homeDeleteAllQuestion => '¿Realmente eliminar todos los mensajes?';
@override
String get homeDeleteAllAction => 'Borrar todo';
@override
String get homeDeleteAllScrubOption => 'Limpiar mensajes';
@override
String get homeDeleteAllSuccess => 'Todos los mensajes eliminados.';
@override
String get homeMarkAllSeenAction => 'Todos leídos';
@override
String get homeMarkAllUnseenAction => 'Todos no leídos';
@override
String get homeFabTooltip => 'Nuevo mensaje';
@override
String get homeLoadingMessageSourceTitle => 'Cargando...';
@override
String homeLoading(String name) {
return 'cargando $name...';
}
@override
String get swipeActionToggleRead => 'Marcar como leído/no leídos';
@override
String get swipeActionDelete => 'Eliminar';
@override
String get swipeActionMarkJunk => 'Marcar como basura';
@override
String get swipeActionArchive => 'Archivar';
@override
String get swipeActionFlag => 'Cambiar bandera';
@override
String multipleMovedToJunk(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Marcado $numberString mensajes como basura',
one: 'Un mensaje marcado como basura',
);
return '$_temp0';
}
@override
String multipleMovedToInbox(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '¡Se ha movido $numberString ¡Los mensajes a la bandeja de entrada',
one: '¡Se ha movido un mensaje a la bandeja de entrada',
);
return '$_temp0';
}
@override
String multipleMovedToArchive(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '¡Archivado $numberString ¡Mensajes',
one: '¡Archivado un mensaje',
);
return '$_temp0';
}
@override
String multipleMovedToTrash(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '¡Eliminado $numberString ¡Mensajes',
one: '¡Eliminado un mensaje',
);
return '$_temp0';
}
@override
String get multipleSelectionNeededInfo => 'Por favor, seleccione mensajes primero.';
@override
String multipleSelectionActionFailed(String details) {
return 'Unable to perform action\nDetails: $details';
}
@override
String multipleMoveTitle(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Mover $numberString mensajes',
one: 'Mover mensaje',
);
return '$_temp0';
}
@override
String get messageActionMultipleMarkSeen => 'Marcar como leído';
@override
String get messageActionMultipleMarkUnseen => 'Marcar como no leído';
@override
String get messageActionMultipleMarkFlagged => 'Marcar mensajes';
@override
String get messageActionMultipleMarkUnflagged => 'Desmarcar mensajes';
@override
String get messageActionViewInSafeMode => 'Ver sin contenido externo';
@override
String get emailSenderUnknown => '<sin remitente>';
@override
String get dateRangeFuture => 'futuro';
@override
String get dateRangeTomorrow => 'mañana';
@override
String get dateRangeToday => 'hoy';
@override
String get dateRangeYesterday => 'ayer';
@override
String get dateRangeCurrentWeek => 'esta semana';
@override
String get dateRangeLastWeek => 'semana pasada';
@override
String get dateRangeCurrentMonth => 'este mes';
@override
String get dateRangeLastMonth => 'mes pasado';
@override
String get dateRangeCurrentYear => 'este año';
@override
String get dateRangeLongAgo => 'hace mucho tiempo';
@override
String get dateUndefined => 'indefinido';
@override
String get dateDayToday => 'hoy';
@override
String get dateDayYesterday => 'ayer';
@override
String dateDayLastWeekday(String day) {
return 'último $day';
}
@override
String get drawerEntryAbout => 'Sobre Maily';
@override
String get drawerEntrySettings => 'Ajustes';
@override
String drawerAccountsSectionTitle(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString cuentas',
one: 'Una cuenta',
);
return '$_temp0';
}
@override
String get drawerEntryAddAccount => 'Añadir cuenta';
@override
String get unifiedAccountName => 'Cuenta unificada';
@override
String get unifiedFolderInbox => 'Entrada unificada';
@override
String get unifiedFolderSent => 'Enviado unificado';
@override
String get unifiedFolderDrafts => 'Borradores unificados';
@override
String get unifiedFolderTrash => 'Basura unificada';
@override
String get unifiedFolderArchive => 'Archivo unificado';
@override
String get unifiedFolderJunk => 'Chatarra unificada';
@override
String get folderInbox => 'Entrada';
@override
String get folderSent => 'Enviado';
@override
String get folderDrafts => 'Borradores';
@override
String get folderTrash => 'Basura';
@override
String get folderArchive => 'Archivar';
@override
String get folderJunk => 'Chatarra';
@override
String get folderUnknown => 'Desconocido';
@override
String get viewContentsAction => 'Ver contenido';
@override
String get viewSourceAction => 'Ver fuente';
@override
String get detailsErrorDownloadInfo => 'No se pudo descargar el mensaje.';
@override
String get detailsErrorDownloadRetry => 'Reintentar';
@override
String get detailsHeaderFrom => 'De';
@override
String get detailsHeaderTo => 'A';
@override
String get detailsHeaderCc => 'CC';
@override
String get detailsHeaderBcc => 'BCC';
@override
String get detailsHeaderDate => 'Fecha';
@override
String get subjectUndefined => '<sin sujeto>';
@override
String get detailsActionShowImages => 'Mostrar imágenes';
@override
String get detailsNewsletterActionUnsubscribe => 'Desuscribirse';
@override
String get detailsNewsletterActionResubscribe => 'Volver a suscribirse';
@override
String get detailsNewsletterStatusUnsubscribed => 'No suscrito';
@override
String get detailsNewsletterUnsubscribeDialogTitle => 'Cancelar suscripción';
@override
String detailsNewsletterUnsubscribeDialogQuestion(String listName) {
return '¿Quieres darte de baja de la lista de correo $listName?';
}
@override
String get detailsNewsletterUnsubscribeDialogAction => 'Cancelar suscripción';
@override
String get detailsNewsletterUnsubscribeSuccessTitle => 'No suscrito';
@override
String detailsNewsletterUnsubscribeSuccessMessage(String listName) {
return 'Te has dado de baja de la lista de correo $listName.';
}
@override
String get detailsNewsletterUnsubscribeFailureTitle => 'No desuscrito';
@override
String detailsNewsletterUnsubscribeFailureMessage(String listName) {
return 'Lo siento, pero no he podido darte de baja de $listName automáticamente.';
}
@override
String get detailsNewsletterResubscribeDialogTitle => 'Volver a suscribirse';
@override
String detailsNewsletterResubscribeDialogQuestion(String listName) {
return '¿Quieres suscribirte de nuevo a esta lista de correo $listName?';
}
@override
String get detailsNewsletterResubscribeDialogAction => 'Suscribirse';
@override
String get detailsNewsletterResubscribeSuccessTitle => 'Suscrito';
@override
String detailsNewsletterResubscribeSuccessMessage(String listName) {
return 'Ahora estás suscrito a la lista de correo $listName de nuevo.';
}
@override
String get detailsNewsletterResubscribeFailureTitle => 'No suscrito';
@override
String detailsNewsletterResubscribeFailureMessage(String listName) {
return 'Lo sentimos, pero la solicitud de suscripción ha fallado para la lista de correo $listName.';
}
@override
String get detailsSendReadReceiptAction => 'Enviar recibo de lectura';
@override
String get detailsReadReceiptSentStatus => 'Leer el recibo enviado ✔️';
@override
String get detailsReadReceiptSubject => 'Leer recibo';
@override
String get attachmentActionOpen => 'Abrir';
@override
String attachmentDecodeError(String details) {
return 'Este archivo adjunto tiene un formato o codificación no compatibles.\nDetalles: \$$details';
}
@override
String attachmentDownloadError(String details) {
return 'No se puede descargar este adjunto.\nDetalles: \$$details';
}
@override
String get messageActionReply => 'Responder';
@override
String get messageActionReplyAll => 'Responder a todos';
@override
String get messageActionForward => 'Reenviar';
@override
String get messageActionForwardAsAttachment => 'Reenviar como archivo adjunto';
@override
String messageActionForwardAttachments(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: 'Reenviar $numberString archivos adjuntos',
one: '¡Adelante el adjunto',
);
return '$_temp0';
}
@override
String get messagesActionForwardAttachments => 'Reenviar archivos adjuntos';
@override
String get messageActionDelete => 'Eliminar';
@override
String get messageActionMoveToInbox => 'Mover a bandeja de entrada';
@override
String get messageActionMove => 'Mover';
@override
String get messageStatusSeen => 'Es leído';
@override
String get messageStatusUnseen => 'No es leído';
@override
String get messageStatusFlagged => 'Está marcado';
@override
String get messageStatusUnflagged => 'No está marcado';
@override
String get messageActionMarkAsJunk => 'Marcar como basura';
@override
String get messageActionMarkAsNotJunk => 'Marcar como no basura';
@override
String get messageActionArchive => 'Archivar';
@override
String get messageActionUnarchive => 'Mover a bandeja de entrada';
@override
String get messageActionRedirect => 'Redireccionar';
@override
String get messageActionAddNotification => 'Añadir notificación';
@override
String get resultDeleted => 'Eliminado';
@override
String get resultMovedToJunk => 'Marcado como basura';
@override
String get resultMovedToInbox => 'Movido a la bandeja de entrada';
@override
String get resultArchived => 'Archivado';
@override
String get resultRedirectedSuccess => 'Mensaje redireccionado 👍';
@override
String resultRedirectedFailure(String details) {
return 'No se puede redirigir el mensaje.\n\nEl servidor respondió con los siguientes detalles: \"$details\"';
}
@override
String get redirectTitle => 'Redireccionar';
@override
String get redirectInfo => 'Redirigir este mensaje a los siguientes destinatarios. Redirigir no altera el mensaje.';
@override
String get redirectEmailInputRequired => 'Necesitas añadir al menos una dirección de correo electrónico válida.';
@override
String searchQueryDescription(String folder) {
return 'Buscar en $folder...';
}
@override
String searchQueryTitle(String query) {
return 'Buscar \"$query\"';
}
@override
String get legaleseUsage => 'Al utilizar Maily aceptas nuestras [PP] y nuestras [TC].';
@override
String get legalesePrivacyPolicy => 'Política de Privacidad';
@override
String get legaleseTermsAndConditions => 'Términos y Condiciones';
@override
String get aboutApplicationLegalese => 'Maily es un software libre publicado bajo la Licencia Pública General GNU.';
@override
String get feedbackActionSuggestFeature => 'Sugerir una característica';
@override
String get feedbackActionReportProblem => 'Reportar un problema';
@override
String get feedbackActionHelpDeveloping => 'Ayuda al desarrollo de Maily';
@override
String get feedbackTitle => 'Comentarios';
@override
String get feedbackIntro => '¡Gracias por probar Maily!';
@override
String get feedbackProvideInfoRequest => 'Por favor, proporcione esta información cuando reporte un problema:';
@override
String get feedbackResultInfoCopied => 'Copiado al portapapeles';
@override
String get accountsTitle => 'Cuentas';
@override
String get accountsActionReorder => 'Reordenar cuentas';
@override
String get settingsTitle => 'Ajustes';
@override
String get settingsSecurityBlockExternalImages => 'Bloquear imágenes externas';
@override
String get settingsSecurityBlockExternalImagesDescriptionTitle => 'Imágenes externas';
@override
String get settingsSecurityBlockExternalImagesDescriptionText => 'Los mensajes de correo electrónico pueden contener imágenes que están integradas o alojadas en servidores externos. Este último, imágenes externas pueden exponer información al remitente del mensaje, por ejemplo, para que el remitente sepa que ha abierto el mensaje. Esta opción le permite bloquear dichas imágenes externas, lo que reduce el riesgo de exponer información confidencial. Todavía puede optar por cargar dichas imágenes por mensaje cuando lea un mensaje.';
@override
String get settingsSecurityMessageRenderingHtml => 'Mostrar contenido completo del mensaje';
@override
String get settingsSecurityMessageRenderingPlainText => 'Mostrar sólo el texto de los mensajes';
@override
String get settingsSecurityLaunchModeLabel => '¿Cómo debe abrir enlaces Maily?';
@override
String get settingsSecurityLaunchModeExternal => 'Abrir enlaces externamente';
@override
String get settingsSecurityLaunchModeInApp => 'Abrir enlaces en Maily';
@override
String get settingsActionAccounts => 'Administrar cuentas';
@override
String get settingsActionDesign => 'Apariencia';
@override
String get settingsActionFeedback => 'Proporcionar comentarios';
@override
String get settingsActionWelcome => 'Mostrar bienvenida';
@override
String get settingsReadReceipts => 'Leer recibos';
@override
String get readReceiptsSettingsIntroduction => '¿Quieres mostrar las solicitudes de recibos de lectura?';
@override
String get readReceiptOptionAlways => 'Siempre';
@override
String get readReceiptOptionNever => 'Nunca';
@override
String get settingsFolders => 'Carpetas';
@override
String get folderNamesIntroduction => '¿Qué nombres prefiere para sus carpetas?';
@override
String get folderNamesSettingLocalized => 'Nombres dados por Maily';
@override
String get folderNamesSettingServer => 'Nombres dados por el servicio';
@override
String get folderNamesSettingCustom => 'Mis nombres personalizados';
@override
String get folderNamesEditAction => 'Editar nombres personalizados';
@override
String get folderNamesCustomTitle => 'Nombres personalizados';
@override
String get folderAddAction => 'Crear carpeta';
@override
String get folderAddTitle => 'Crear carpeta';
@override
String get folderAddNameLabel => 'Nombre';
@override
String get folderAddNameHint => 'Nombre de la nueva carpeta';
@override
String get folderAccountLabel => 'Cuenta';
@override
String get folderMailboxLabel => 'Carpeta';
@override
String get folderAddResultSuccess => 'Carpeta creada 😊';
@override
String folderAddResultFailure(String details) {
return 'No se pudo crear la carpeta.\n\nEl servidor respondió con $details';
}
@override
String get folderDeleteAction => 'Eliminar';
@override
String get folderDeleteConfirmTitle => 'Confirmar';
@override
String folderDeleteConfirmText(String name) {
return '¿Realmente desea eliminar la carpeta $name?';
}
@override
String get folderDeleteResultSuccess => 'Carpeta eliminada.';
@override
String folderDeleteResultFailure(String details) {
return 'No se ha podido eliminar la carpeta.\n\nEl servidor ha respondido con $details';
}
@override
String get settingsDevelopment => 'Configuración de desarrollo';
@override
String get developerModeTitle => 'Modo de desarrollo';
@override
String get developerModeIntroduction => 'Si activas el modo de desarrollo podrás ver el código fuente de los mensajes y convertir los archivos adjuntos de texto a mensajes.';
@override
String get developerModeEnable => 'Activar modo de desarrollo';
@override
String get developerShowAsEmail => 'Convertir texto a email';
@override
String get developerShowAsEmailFailed => 'Este texto no se puede convertir en un mensaje MIME.';
@override
String get designTitle => 'Ajustes de diseño';
@override
String get designSectionThemeTitle => 'Tema';
@override
String get designThemeOptionLight => 'Luz';
@override
String get designThemeOptionDark => 'Oscuro';
@override
String get designThemeOptionSystem => 'Sistema';
@override
String get designThemeOptionCustom => 'Personalizado';
@override
String get designSectionCustomTitle => 'Activar tema oscuro';
@override
String designThemeCustomStart(String time) {
return 'de $time';
}
@override
String designThemeCustomEnd(String time) {
return 'hasta $time';
}
@override
String get designSectionColorTitle => 'Esquema de color';
@override
String get securitySettingsTitle => 'Seguridad';
@override
String get securitySettingsIntro => 'Adapte la configuración de seguridad a sus necesidades personales.';
@override
String get securityUnlockWithFaceId => 'Desbloquea Maily con Face ID.';
@override
String get securityUnlockWithTouchId => 'Desbloquea Maily con Touch ID.';
@override
String get securityUnlockReason => 'Desbloquea Maily.';
@override
String get securityUnlockDisableReason => 'Desbloquear Maily para desactivar el bloqueo.';
@override
String get securityUnlockNotAvailable => 'Su dispositivo no soporta biométricos, posiblemente necesite configurar las opciones de desbloqueo primero.';
@override
String get securityUnlockLabel => 'Bloquear Maily';
@override
String get securityUnlockDescriptionTitle => 'Bloquear Maily';
@override
String get securityUnlockDescriptionText => 'Puedes elegir bloquear el acceso a Maily, para que otros no puedan leer tu correo electrónico incluso cuando tengan acceso a tu dispositivo.';
@override
String get securityLockImmediately => 'Bloquear inmediatamente';
@override
String get securityLockAfter5Minutes => 'Bloquear después de 5 minutos';
@override
String get securityLockAfter30Minutes => 'Bloquear después de 30 minutos';
@override
String get lockScreenTitle => 'Maily está bloqueado';
@override
String get lockScreenIntro => 'Maily está bloqueado, por favor autentifíquese para continuar.';
@override
String get lockScreenUnlockAction => 'Desbloquear';
@override
String get addAccountTitle => 'Añadir cuenta';
@override
String get addAccountEmailLabel => 'E-mail';
@override
String get addAccountEmailHint => 'Introduzca su dirección de correo electrónico';
@override
String addAccountResolvingSettingsLabel(String email) {
return 'Resolviendo $email...';
}
@override
String addAccountResolvedSettingsWrongAction(String provider) {
return '¿No está en $provider?';
}
@override
String addAccountResolvingSettingsFailedInfo(String email) {
return 'No se puede resolver $email. Por favor, vuelve a cambiarlo o configura la cuenta manualmente.';
}
@override
String get addAccountEditManuallyAction => 'Editar manualmente';
@override
String get addAccountPasswordLabel => 'Contraseña';
@override
String get addAccountPasswordHint => 'Por favor, introduce tu contraseña';
@override
String get addAccountApplicationPasswordRequiredInfo => 'Este proveedor requiere que establezcas una contraseña específica para la aplicación.';
@override
String get addAccountApplicationPasswordRequiredButton => 'Crear contraseña específica de la aplicación';
@override
String get addAccountApplicationPasswordRequiredAcknowledged => 'Ya tengo una contraseña de la aplicación';
@override
String get addAccountVerificationStep => 'Verificación';
@override
String get addAccountSetupAccountStep => 'Configuracion de Cuenta';
@override
String addAccountVerifyingSettingsLabel(String email) {
return 'Verificando $email...';
}
@override
String addAccountVerifyingSuccessInfo(String email) {
return 'Has iniciado sesión con éxito en $email.';
}
@override
String addAccountVerifyingFailedInfo(String email) {
return 'Lo sentimos, pero ha habido un problema. Por favor, comprueba tu correo electrónico $email y contraseña.';
}
@override
String addAccountOauthOptionsText(String provider) {
return 'Inicie sesión con $provider o cree una contraseña específica de la aplicación.';
}
@override
String addAccountOauthSignIn(String provider) {
return 'Iniciar sesión con $provider';
}
@override
String get addAccountOauthSignInGoogle => 'Iniciar sesión con Google';
@override
String get addAccountOauthSignInWithAppPassword => 'Alternativamente, cree una contraseña de la aplicación para iniciar sesión.';
@override
String get accountAddImapAccessSetupMightBeRequired => 'Su proveedor puede requerir que configure el acceso para aplicaciones de correo electrónico manualmente.';
@override
String get addAccountSetupImapAccessButtonLabel => 'Configurar acceso a email';
@override
String get addAccountNameOfUserLabel => 'Tu nombre';
@override
String get addAccountNameOfUserHint => 'El nombre que los destinatarios ven';
@override
String get addAccountNameOfAccountLabel => 'Nombre de cuenta';
@override
String get addAccountNameOfAccountHint => 'Introduce el nombre de tu cuenta';
@override
String editAccountTitle(String name) {
return 'Editar $name';
}
@override
String editAccountFailureToConnectInfo(String name) {
return 'Maily no pudo conectar $name.';
}
@override
String get editAccountFailureToConnectRetryAction => 'Reintentar';
@override
String get editAccountFailureToConnectChangePasswordAction => 'Cambiar contraseña';
@override
String get editAccountFailureToConnectFixedTitle => 'Conectado';
@override
String get editAccountFailureToConnectFixedInfo => 'La cuenta está conectada de nuevo.';
@override
String get editAccountIncludeInUnifiedLabel => 'Incluye en cuenta unificada';
@override
String editAccountAliasLabel(String email) {
return 'Direcciones de correo electrónico de $email:';
}
@override
String get editAccountNoAliasesInfo => 'Aún no tienes alias conocidos para esta cuenta.';
@override
String editAccountAliasRemoved(String email) {
return 'Alias $email eliminado';
}
@override
String get editAccountAddAliasAction => 'Añadir alias';
@override
String get editAccountPlusAliasesSupported => 'Soporta + alias';
@override
String get editAccountCheckPlusAliasAction => 'Prueba de soporte para + alias';
@override
String get editAccountBccMyself => 'BCC mismo';
@override
String get editAccountBccMyselfDescriptionTitle => 'BCC mismo';
@override
String get editAccountBccMyselfDescriptionText => 'Puedes enviar automáticamente mensajes a ti mismo para cada mensaje que envíes desde esta cuenta con la función \"BCC yo\". Normalmente esto no es necesario y deseado, ya que todos los mensajes salientes se almacenan en la carpeta \"Enviado\" de todos modos.';
@override
String get editAccountServerSettingsAction => 'Editar configuración del servidor';
@override
String get editAccountDeleteAccountAction => 'Eliminar cuenta';
@override
String get editAccountDeleteAccountConfirmationTitle => 'Confirmar';
@override
String editAccountDeleteAccountConfirmationQuery(String name) {
return '¿Quieres eliminar la cuenta $name?';
}
@override
String editAccountTestPlusAliasTitle(String name) {
return '+ Alias para $name';
}
@override
String get editAccountTestPlusAliasStepIntroductionTitle => 'Introducción';
@override
String editAccountTestPlusAliasStepIntroductionText(String accountName, String example) {
return 'Tu cuenta $accountName podría ser compatible con los alias + llamados como $example.\nUn alias A + te ayuda a proteger tu identidad y te ayuda contra el spam.\nPara probarlo, se enviará un mensaje de prueba a esta dirección generada. Si llega, su proveedor soporta + alias y puede generarlos fácilmente a petición al escribir un nuevo mensaje de correo.';
}
@override
String get editAccountTestPlusAliasStepTestingTitle => 'Pruebas';
@override
String get editAccountTestPlusAliasStepResultTitle => 'Resultado';
@override
String editAccountTestPlusAliasStepResultSuccess(String name) {
return 'Tu cuenta $name soporta + alias.';
}
@override
String editAccountTestPlusAliasStepResultNoSuccess(String name) {
return 'Tu cuenta $name no soporta + alias.';
}
@override
String get editAccountAddAliasTitle => 'Añadir alias';
@override
String get editAccountEditAliasTitle => 'Editar alias';
@override
String get editAccountAliasAddAction => 'Añadir';
@override
String get editAccountAliasUpdateAction => 'Actualizar';
@override
String get editAccountEditAliasNameLabel => 'Nombre del alias';
@override
String get editAccountEditAliasEmailLabel => 'Alias email';
@override
String get editAccountEditAliasEmailHint => 'Tu dirección de email de alias';
@override
String editAccountEditAliasDuplicateError(String email) {
return 'Ya hay un alias con $email.';
}
@override
String get editAccountEnableLogging => 'Activar registro';
@override
String get editAccountLoggingEnabled => 'Registro habilitado, por favor reinicie';
@override
String get editAccountLoggingDisabled => 'Registro desactivado, por favor reinicie';
@override
String get accountDetailsFallbackTitle => 'Ajustes del servidor';
@override
String get errorTitle => 'Error';
@override
String get accountProviderStepTitle => 'Proveedor de Servicio de Email';
@override
String get accountProviderCustom => 'Otro servicio de email';
@override
String accountDetailsErrorHostProblem(String incomingHost, String outgoingHost) {
return 'Maily no puede llegar al servidor de correo especificado. Por favor, compruebe la configuración del servidor de entrada \"$incomingHost\" y la configuración del servidor de salida \"$outgoingHost\".';
}
@override
String accountDetailsErrorLoginProblem(String userName, String password) {
return 'No se puede iniciar sesión. Por favor, comprueba tu nombre de usuario \"$userName\" y tu contraseña \"$password\".';
}
@override
String get accountDetailsUserNameLabel => 'Nombre de usuario';
@override
String get accountDetailsUserNameHint => 'Su nombre de usuario, si es diferente del correo electrónico';
@override
String get accountDetailsPasswordLabel => 'Contraseña de acceso';
@override
String get accountDetailsPasswordHint => 'Su contraseña';
@override
String get accountDetailsBaseSectionTitle => 'Ajustes de base';
@override
String get accountDetailsIncomingLabel => 'Servidor entrante';
@override
String get accountDetailsIncomingHint => 'Dominio como imap.domain.com';
@override
String get accountDetailsOutgoingLabel => 'Servidor saliente';
@override
String get accountDetailsOutgoingHint => 'Dominio como smtp.domain.com';
@override
String get accountDetailsAdvancedIncomingSectionTitle => 'Configuración avanzada de entrada';
@override
String get accountDetailsIncomingServerTypeLabel => 'Tipo de entrada:';
@override
String get accountDetailsOptionAutomatic => 'automático';
@override
String get accountDetailsIncomingSecurityLabel => 'Seguridad entrante:';
@override
String get accountDetailsSecurityOptionNone => 'Plain (sin cifrado)';
@override
String get accountDetailsIncomingPortLabel => 'Puerto entrante';
@override
String get accountDetailsPortHint => 'Dejar en blanco para determinar automáticamente';
@override
String get accountDetailsIncomingUserNameLabel => 'Nombre de usuario entrante';
@override
String get accountDetailsAlternativeUserNameHint => 'Tu nombre de usuario, si es diferente de arriba';
@override
String get accountDetailsIncomingPasswordLabel => 'Contraseña entrante';
@override
String get accountDetailsAlternativePasswordHint => 'Su contraseña, si es diferente de la anterior';
@override
String get accountDetailsAdvancedOutgoingSectionTitle => 'Ajustes avanzados de salida';
@override
String get accountDetailsOutgoingServerTypeLabel => 'Tipo saliente:';
@override
String get accountDetailsOutgoingSecurityLabel => 'Seguridad saliente:';
@override
String get accountDetailsOutgoingPortLabel => 'Puerto saliente';
@override
String get accountDetailsOutgoingUserNameLabel => 'Nombre de usuario saliente';
@override
String get accountDetailsOutgoingPasswordLabel => 'Contraseña saliente';
@override
String get composeTitleNew => 'Nuevo mensaje';
@override
String get composeTitleForward => 'Reenviar';
@override
String get composeTitleReply => 'Responder';
@override
String get composeEmptyMessage => 'mensaje vacío';
@override
String get composeWarningNoSubject => 'No ha especificado un asunto. ¿Desea enviar el mensaje sin un asunto?';
@override
String get composeActionSentWithoutSubject => 'Enviar';
@override
String get composeMailSendSuccess => 'Email enviado 😊';
@override
String composeSendErrorInfo(String details) {
return 'Lo sentimos, no se ha podido enviar tu correo. Hemos recibido el siguiente error:\n$details.';
}
@override
String get composeRequestReadReceiptAction => 'Solicitar recibo de lectura';
@override
String get composeSaveDraftAction => 'Guardar como borrador';
@override
String get composeMessageSavedAsDraft => 'Borrador guardado';
@override
String composeMessageSavedAsDraftErrorInfo(String details) {
return 'No se ha podido guardar tu borrador con el siguiente error:\n$details';
}
@override
String get composeConvertToPlainTextEditorAction => 'Convertir a texto plano';
@override
String get composeConvertToHtmlEditorAction => 'Convertir a mensaje enriquecido (HTML)';
@override
String get composeContinueEditingAction => 'Continuar editando';
@override
String get composeCreatePlusAliasAction => 'Crear nuevos + alias...';
@override
String get composeSenderHint => 'Remitente';
@override
String get composeRecipientHint => 'Email del destinatario';
@override
String get composeSubjectLabel => 'Sujeto';
@override
String get composeSubjectHint => 'Asunto del mensaje';
@override
String get composeAddAttachmentAction => 'Añadir';
@override
String composeRemoveAttachmentAction(String name) {
return 'Eliminar $name';
}
@override
String get composeLeftByMistake => '¿Dejado por error?';
@override
String get attachTypeFile => 'Fichero';
@override
String get attachTypePhoto => 'Foto';
@override
String get attachTypeVideo => 'Vídeo';
@override
String get attachTypeAudio => 'Audio';
@override
String get attachTypeLocation => 'Ubicación';
@override
String get attachTypeGif => 'Gif animado';
@override
String get attachTypeGifSearch => 'buscar GIPHY';
@override
String get attachTypeSticker => 'Pegatina';
@override
String get attachTypeStickerSearch => 'buscar GIPHY';
@override
String get attachTypeAppointment => 'Cita';
@override
String get languageSettingTitle => 'Idioma';
@override
String get languageSettingLabel => 'Elige el idioma para Maily:';
@override
String get languageSettingSystemOption => 'Idioma del sistema';
@override
String get languageSettingConfirmationTitle => '¿Usar Inglés para Maily?';
@override
String get languageSettingConfirmationQuery => 'Por favor confirme el uso del inglés como idioma elegido.';
@override
String get languageSetInfo => 'Ahora se muestra en inglés. Por favor, reinicia la aplicación para que surta efecto.';
@override
String get languageSystemSetInfo => 'Maily ahora utilizará el idioma del sistema o Inglés si el idioma del sistema no es compatible.';
@override
String get swipeSettingTitle => 'Deslizar gestos';
@override
String get swipeSettingLeftToRightLabel => 'Deslizar de izquierda a derecha';
@override
String get swipeSettingRightToLeftLabel => 'Deslizar derecha a izquierda';
@override
String get swipeSettingChangeAction => 'Cambiar';
@override
String get signatureSettingsTitle => 'Firma';
@override
String get signatureSettingsComposeActionsInfo => 'Activar la firma para los siguientes mensajes:';
@override
String get signatureSettingsAccountInfo => 'Puede especificar firmas específicas de la cuenta en la configuración de la cuenta.';
@override
String signatureSettingsAddForAccount(String account) {
return 'Añadir firma para $account';
}
@override
String get defaultSenderSettingsTitle => 'Remitente por defecto';
@override
String get defaultSenderSettingsLabel => 'Seleccione el remitente para nuevos mensajes.';
@override
String defaultSenderSettingsFirstAccount(String email) {
return 'Primera cuenta ($email)';
}
@override
String get defaultSenderSettingsAliasInfo => 'Puede configurar direcciones de alias de correo electrónico en la [AS].';
@override
String get defaultSenderSettingsAliasAccountSettings => 'configuración de cuenta';
@override
String get replySettingsTitle => 'Formato de mensaje';
@override
String get replySettingsIntro => '¿En qué formato desea responder o reenviar el correo electrónico por defecto?';
@override
String get replySettingsFormatHtml => 'Formato siempre rico (HTML)';
@override
String get replySettingsFormatSameAsOriginal => 'Usar el mismo formato que el correo original';
@override
String get replySettingsFormatPlainText => 'Siempre sólo texto';
@override
String get moveTitle => 'Mover mensaje';
@override
String moveSuccess(String mailbox) {
return 'Mensajes movidos a $mailbox.';
}
@override
String get editorArtInputLabel => 'Tu entrada';
@override
String get editorArtInputHint => 'Introduce el texto aquí';
@override
String get editorArtWaitingForInputHint => 'esperando por entrada...';
@override
String get fontSerifBold => 'Serif bold';
@override
String get fontSerifItalic => 'Serif italic';
@override
String get fontSerifBoldItalic => 'Serif bold italic';
@override
String get fontSans => 'Sans';
@override
String get fontSansBold => 'Sans bold';
@override
String get fontSansItalic => 'Sans italic';
@override
String get fontSansBoldItalic => 'Sans bold italic';
@override
String get fontScript => 'Escribir';
@override
String get fontScriptBold => 'Escribir negrita';
@override
String get fontFraktur => 'Fraktur';
@override
String get fontFrakturBold => 'Fraktur bold';
@override
String get fontMonospace => 'Monoespaciado';
@override
String get fontFullwidth => 'Ancho completo';
@override
String get fontDoublestruck => 'Doble golpeado';
@override
String get fontCapitalized => 'Capitalizado';
@override
String get fontCircled => 'Circlado';
@override
String get fontParenthesized => 'Parentesizado';
@override
String get fontUnderlinedSingle => 'Subrayado';
@override
String get fontUnderlinedDouble => 'Doble subrayado';
@override
String get fontStrikethroughSingle => 'Golpear a través';
@override
String get fontCrosshatch => 'Crosshatch';
@override
String accountLoadError(String name) {
return 'No se puede conectar a su cuenta $name. ¿Ha cambiado la contraseña?';
}
@override
String get accountLoadErrorEditAction => 'Editar cuenta';
@override
String get extensionsTitle => 'Extensiones';
@override
String get extensionsIntro => 'Con los proveedores de servicios de correo electrónico de extensiones, las empresas y los desarrolladores pueden adaptarse a las funcionalidades más útiles.';
@override
String get extensionsLearnMoreAction => 'Más información sobre extensiones';
@override
String get extensionsReloadAction => 'Recargar extensiones';
@override
String get extensionDeactivateAllAction => 'Desactivar todas las extensiones';
@override
String get extensionsManualAction => 'Cargar manualmente';
@override
String get extensionsManualUrlLabel => 'Url de la extensión';
@override
String extensionsManualLoadingError(String url) {
return 'No se ha podido descargar la extensión de \"$url\".';
}
@override
String get icalendarAcceptTentatively => 'Tentativamente';
@override
String get icalendarActionChangeParticipantStatus => 'Cambiar';
@override
String get icalendarLabelSummary => 'Título';
@override
String get icalendarNoSummaryInfo => '(sin título)';
@override
String get icalendarLabelDescription => 'Descripción';
@override
String get icalendarLabelStart => 'Comenzar';
@override
String get icalendarLabelEnd => 'Fin';
@override
String get icalendarLabelDuration => 'Duración';
@override
String get icalendarLabelLocation => 'Ubicación';
@override
String get icalendarLabelTeamsUrl => 'Enlace';
@override
String get icalendarLabelRecurrenceRule => 'Repetir';
@override
String get icalendarLabelParticipants => 'Participantes';
@override
String get icalendarParticipantStatusNeedsAction => 'Se le pide que responda a esta invitación.';
@override
String get icalendarParticipantStatusAccepted => 'Has aceptado esta invitación.';
@override
String get icalendarParticipantStatusDeclined => 'Has rechazado esta invitación.';
@override
String get icalendarParticipantStatusAcceptedTentatively => 'Has aceptado esta invitación de forma tentativa.';
@override
String get icalendarParticipantStatusDelegated => 'Usted ha delegado esta invitación.';
@override
String get icalendarParticipantStatusInProcess => 'La tarea está en curso.';
@override
String get icalendarParticipantStatusPartial => 'La tarea está parcialmente hecha.';
@override
String get icalendarParticipantStatusCompleted => 'La tarea está hecha.';
@override
String get icalendarParticipantStatusOther => 'Su estado es desconocido.';
@override
String get icalendarParticipantStatusChangeTitle => 'Tu estado';
@override
String get icalendarParticipantStatusChangeText => '¿Quieres aceptar esta invitación?';
@override
String icalendarParticipantStatusSentFailure(String details) {
return 'No se puede enviar la respuesta.\nEl servidor respondió con los siguientes detalles:\n$details';
}
@override
String get icalendarExportAction => 'Exportar';
@override
String icalendarReplyStatusNeedsAction(String attendee) {
return '$attendee no ha respondido a esta invitación.';
}
@override
String icalendarReplyStatusAccepted(String attendee) {
return '$attendee ha aceptado la cita.';
}
@override
String icalendarReplyStatusDeclined(String attendee) {
return '$attendee ha rechazado esta invitación.';
}
@override
String icalendarReplyStatusAcceptedTentatively(String attendee) {
return '$attendee ha aceptado tentativamente esta invitación.';
}
@override
String icalendarReplyStatusDelegated(String attendee) {
return '$attendee ha delegado esta invitación.';
}
@override
String icalendarReplyStatusInProcess(String attendee) {
return '$attendee ha iniciado esta tarea.';
}
@override
String icalendarReplyStatusPartial(String attendee) {
return '$attendee ha realizado parcialmente esta tarea.';
}
@override
String icalendarReplyStatusCompleted(String attendee) {
return '$attendee ha finalizado esta tarea.';
}
@override
String icalendarReplyStatusOther(String attendee) {
return '$attendee ha respondido con un estado desconocido.';
}
@override
String get icalendarReplyWithoutParticipants => 'Esta respuesta de calendario no contiene participantes.';
@override
String icalendarReplyWithoutStatus(String attendee) {
return '$attendee respondió sin un estado de participación.';
}
@override
String get composeAppointmentTitle => 'Crear cita';
@override
String get composeAppointmentLabelDay => 'día';
@override
String get composeAppointmentLabelTime => 'tiempo';
@override
String get composeAppointmentLabelAllDayEvent => 'Todo el día';
@override
String get composeAppointmentLabelRepeat => 'Repetir';
@override
String get composeAppointmentLabelRepeatOptionNever => 'Nunca';
@override
String get composeAppointmentLabelRepeatOptionDaily => 'Diario';
@override
String get composeAppointmentLabelRepeatOptionWeekly => 'Semanal';
@override
String get composeAppointmentLabelRepeatOptionMonthly => 'Mensual';
@override
String get composeAppointmentLabelRepeatOptionYearly => 'Anualmente';
@override
String get composeAppointmentRecurrenceFrequencyLabel => 'Frecuencia';
@override
String get composeAppointmentRecurrenceIntervalLabel => 'Intervalo';
@override
String get composeAppointmentRecurrenceDaysLabel => 'En días';
@override
String get composeAppointmentRecurrenceUntilLabel => 'Hasta';
@override
String get composeAppointmentRecurrenceUntilOptionUnlimited => 'Sin límite';
@override
String composeAppointmentRecurrenceUntilOptionRecommended(String duration) {
return 'Recomendado ($duration)';
}
@override
String get composeAppointmentRecurrenceUntilOptionSpecificDate => 'Hasta la fecha elegida';
@override
String composeAppointmentRecurrenceMonthlyOnDayOfMonth(int day) {
final intl.NumberFormat dayNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String dayString = dayNumberFormat.format(day);
return 'El $dayString. día del mes';
}
@override
String get composeAppointmentRecurrenceMonthlyOnWeekDay => 'Día de la semana en mes';
@override
String get composeAppointmentRecurrenceFirst => 'Primero';
@override
String get composeAppointmentRecurrenceSecond => 'Segundo';
@override
String get composeAppointmentRecurrenceThird => 'Tercer';
@override
String get composeAppointmentRecurrenceLast => 'Último';
@override
String get composeAppointmentRecurrenceSecondLast => 'Segundo-último';
@override
String durationYears(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString años',
one: '1 año',
);
return '$_temp0';
}
@override
String durationMonths(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString meses',
one: '1 mes',
);
return '$_temp0';
}
@override
String durationWeeks(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString semanas',
one: '1 semana',
);
return '$_temp0';
}
@override
String durationDays(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString días',
one: '1 día',
);
return '$_temp0';
}
@override
String durationHours(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString horas',
one: '1 hora',
);
return '$_temp0';
}
@override
String durationMinutes(int number) {
final intl.NumberFormat numberNumberFormat = intl.NumberFormat.compactLong(
locale: localeName,
);
final String numberString = numberNumberFormat.format(number);
String _temp0 = intl.Intl.pluralLogic(
number,
locale: localeName,
other: '$numberString minutos',
one: '1 minuto',
);
return '$_temp0';
}
@override
String get durationEmpty => 'Sin duración';
}
| 0
|
mirrored_repositories/enough_mail_app/test
|
mirrored_repositories/enough_mail_app/test/model/multiple_message_source_test.dart
|
// ignore_for_file: lines_longer_than_80_chars
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_mail_app/src/account/model.dart';
import 'package:enough_mail_app/src/localization/app_localizations.g.dart';
import 'package:enough_mail_app/src/localization/app_localizations_en.g.dart';
import 'package:enough_mail_app/src/models/async_mime_source.dart';
import 'package:enough_mail_app/src/models/message.dart';
import 'package:enough_mail_app/src/models/message_source.dart';
import 'package:enough_mail_app/src/notification/model.dart';
import 'package:enough_mail_app/src/notification/service.dart';
import 'package:enough_mail_app/src/scaffold_messenger/service.dart';
import 'package:enough_mail_app/src/widgets/cupertino_status_bar.dart';
import 'package:flutter/src/material/scaffold.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get_it/get_it.dart';
import 'package:mocktail/mocktail.dart';
import 'fake_mime_source.dart';
class MockUnifiedAccount extends Mock implements UnifiedAccount {}
void main() async {
final notificationService = TestNotificationService();
GetIt.instance.registerSingleton<NotificationService>(notificationService);
GetIt.instance.registerLazySingleton<ScaffoldMessengerService>(
TestScaffoldMessengerService.new,
);
final firstMimeSourceStartDate = DateTime.utc(2022, 04, 16, 09);
const firstMimeSourceDifferencePerMessage = Duration(minutes: 5);
final secondMimeSourceStartDate = DateTime.utc(2022, 04, 16, 09, 01);
const secondMimeSourceDifferencePerMessage = Duration(minutes: 10);
late AsyncMimeSource firstMimeSource;
late AsyncMimeSource secondMimeSource;
late MultipleMessageSource source;
setUp(() {
firstMimeSource = FakeMimeSource(
size: 100,
name: 'first',
startDate: firstMimeSourceStartDate,
differencePerMessage: firstMimeSourceDifferencePerMessage,
);
secondMimeSource = FakeMimeSource(
size: 20,
name: 'second',
startDate: secondMimeSourceStartDate,
differencePerMessage: secondMimeSourceDifferencePerMessage,
);
source = MultipleMessageSource(
[firstMimeSource, secondMimeSource],
'multiple',
MailboxFlag.inbox,
account: MockUnifiedAccount(),
);
});
Future<void> expectMessagesOrderedByDate({int numberToTest = 20}) async {
var lastDate = DateTime.now();
var lastSubject = '<no message>';
for (int i = 0; i < numberToTest; i++) {
final message = await source.getMessageAt(i);
final messageDate = message.mimeMessage.decodeDate();
final subject =
message.mimeMessage.decodeSubject() ?? '<no subject for $i>';
expect(
messageDate,
isNotNull,
reason: 'no date for message at index $i $subject',
);
expect(
messageDate?.isBefore(lastDate),
isTrue,
reason:
'wrong date for message at $i: $messageDate of "$subject" should be before $lastDate of "$lastSubject"',
);
lastDate = messageDate ?? DateTime.now();
lastSubject = subject;
}
}
group('base tests', () {
test('size', () async {
expect(source.size, 120);
});
test('load first message', () async {
final message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
});
test('load second message', () async {
final message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
});
test('load third message', () async {
final message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 99);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 99');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.subtract(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
});
test('load fourth message', () async {
final message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 19);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 19');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.subtract(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
});
test('ensure dates are strictly ordered', () async {
DateTime? lastDateTime =
(await source.getMessageAt(0)).mimeMessage.decodeDate();
expect(lastDateTime, isNotNull);
for (int i = 1; i < source.size; i++) {
final nextDateTime =
(await source.getMessageAt(i)).mimeMessage.decodeDate();
expect(
nextDateTime,
isNotNull,
reason: 'decodeDate() is null for message $i',
);
expect(
nextDateTime?.isBefore(lastDateTime ?? DateTime.now()),
isTrue,
reason: '$nextDateTime should be before $lastDateTime for message $i',
);
lastDateTime = nextDateTime;
}
});
});
group('incoming messages', () {
test('simple onMessageArrived x 1', () async {
await (firstMimeSource as FakeMimeSource).addFakeMessage(101);
final message = await source.getMessageAt(0);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
await expectMessagesOrderedByDate();
});
test('real update - onMessageArrived x 1', () async {
var hasBeenNotified = false;
source.addListener(() {
hasBeenNotified = true;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
// add new message:
await (firstMimeSource as FakeMimeSource).addFakeMessage(101);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 101);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
expect(hasBeenNotified, isTrue);
});
test('real update 1 x- test first 2 messages', () async {
var hasBeenNotified = false;
source.addListener(() {
hasBeenNotified = true;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
// add new message:
await (firstMimeSource as FakeMimeSource).addFakeMessage(101);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 101);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
expect(hasBeenNotified, isTrue);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
});
test('onMessageArrived x 2', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
// add new message:
await (firstMimeSource as FakeMimeSource).addFakeMessage(101);
expect(notifyCounter, 1);
// add new message:
await (secondMimeSource as FakeMimeSource).addFakeMessage(21);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 21);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 21');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.add(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
expect(notifyCounter, 2);
await expectMessagesOrderedByDate();
});
test('onMessageArrived - once per source ordered by data', () async {
var notifyCounter = 0;
source.addListener(() => notifyCounter++);
var message = await source.getMessageAt(0);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
message = await source.getMessageAt(1);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
await (firstMimeSource as FakeMimeSource).addFakeMessage(101);
await (secondMimeSource as FakeMimeSource).addFakeMessage(21);
expect(notifyCounter, 2);
expect(source.size, 122);
message = await source.getMessageAt(0);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 21');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.add(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
await expectMessagesOrderedByDate();
});
test('onMessageArrived - once per source out of date order', () async {
var notifyCounter = 0;
source.addListener(() => notifyCounter++);
var message = await source.getMessageAt(0);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
message = await source.getMessageAt(1);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
await (secondMimeSource as FakeMimeSource).addFakeMessage(21);
await (firstMimeSource as FakeMimeSource).addFakeMessage(101);
expect(notifyCounter, 2);
expect(source.size, 122);
message = await source.getMessageAt(0);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 21');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.add(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
await expectMessagesOrderedByDate();
});
});
group('vanished', () {
test('onMessagesVanished - single and first sequence ID', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
// remove message:
await secondMimeSource.onMessagesVanished(MessageSequence.fromIds([20]));
expect(notifyCounter, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
});
test('onMessagesVanished - second sequence ID', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 99);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 19);
message = await source.getMessageAt(4);
expect(message.mimeMessage.sequenceId, 98);
message = await source.getMessageAt(5);
expect(message.mimeMessage.sequenceId, 97);
// remove message:
await firstMimeSource.onMessagesVanished(MessageSequence.fromIds([100]));
expect(notifyCounter, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 99);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 19);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 98);
message = await source.getMessageAt(4);
expect(message.mimeMessage.sequenceId, 97);
message = await source.getMessageAt(0);
});
test('onMessagesVanished - single and first UID', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
// remove message:
await secondMimeSource
.onMessagesVanished(MessageSequence.fromIds([20], isUid: true));
expect(notifyCounter, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
});
test('onMessagesVanished - second UID', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 99);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 19);
message = await source.getMessageAt(4);
expect(message.mimeMessage.sequenceId, 98);
message = await source.getMessageAt(5);
expect(message.mimeMessage.sequenceId, 97);
// remove message:
await firstMimeSource
.onMessagesVanished(MessageSequence.fromIds([100], isUid: true));
expect(notifyCounter, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 99);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 19);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 98);
message = await source.getMessageAt(4);
expect(message.mimeMessage.sequenceId, 97);
message = await source.getMessageAt(0);
});
test('onMessagesVanished - 2 UIDs', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 99);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 19);
message = await source.getMessageAt(4);
expect(message.mimeMessage.sequenceId, 98);
message = await source.getMessageAt(5);
expect(message.mimeMessage.sequenceId, 97);
// remove message:
await firstMimeSource
.onMessagesVanished(MessageSequence.fromIds([100, 99], isUid: true));
expect(notifyCounter, 2);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 19);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 98);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 97);
message = await source.getMessageAt(4);
expect(message.mimeMessage.sequenceId, 18);
message = await source.getMessageAt(0);
});
});
group('deleteAll', () {
test('size', () async {
expect(source.size, 120);
await source.deleteAllMessages();
expect(source.size, 0);
});
});
group('flags', () {
test('notify seen', () async {
final firstMime = await secondMimeSource.getMessage(0);
expect(firstMime.isSeen, isFalse);
expect(firstMime.sequenceId, isNotNull);
final firstMessage = await source.getMessageAt(0);
expect(firstMessage.mimeMessage.guid, firstMime.guid);
expect(firstMessage.isSeen, isFalse);
var notifyCounter = 0;
firstMessage.addListener(() {
notifyCounter++;
});
final updatedMime = (secondMimeSource as FakeMimeSource)
.createMessage(firstMime.sequenceId ?? 0)
..setFlag(MessageFlags.seen, true);
await secondMimeSource.onMessageFlagsUpdated(updatedMime);
expect(notifyCounter, 1);
expect(firstMessage.isSeen, isTrue);
});
test('notify unseen', () async {
final firstMime = await secondMimeSource.getMessage(0);
firstMime.setFlag(MessageFlags.seen, true);
expect(firstMime.isSeen, isTrue);
expect(firstMime.sequenceId, isNotNull);
final firstMessage = await source.getMessageAt(0);
expect(firstMessage.mimeMessage.guid, firstMime.guid);
expect(firstMessage.isSeen, isTrue);
var notifyCounter = 0;
firstMessage.addListener(() {
notifyCounter++;
});
final updatedMime = (secondMimeSource as FakeMimeSource)
.createMessage(firstMime.sequenceId ?? 0)
..setFlag(MessageFlags.seen, false);
await secondMimeSource.onMessageFlagsUpdated(updatedMime);
expect(notifyCounter, 1);
expect(firstMessage.isSeen, isFalse);
});
});
group('resync manually', () {
test('same messages after resync', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await firstMimeSource.getMessage(i);
messages.add(message);
}
await firstMimeSource.resyncMessagesManually(messages);
expect(source.size, 120);
expect(notifyCounter, 0);
});
test('same re-created messages after resync', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
await source.getMessageAt(0);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message =
(firstMimeSource as FakeMimeSource).createMessage(100 - i);
messages.add(message);
}
await firstMimeSource.resyncMessagesManually(messages);
expect(source.size, 120);
expect(notifyCounter, 0);
});
test('1 new message after resync', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message =
(firstMimeSource as FakeMimeSource).createMessage(101 - i);
messages.add(message);
}
await firstMimeSource.getMessage(0);
await firstMimeSource.resyncMessagesManually(messages);
expect(firstMimeSource.size, 101);
expect(source.size, 121);
expect(notifyCounter, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 101);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
// previous first message should now be at the second position:
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
});
test('1 removed message after resync', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
final messages = <MimeMessage>[];
for (int i = 1; i < 21; i++) {
final message =
(firstMimeSource as FakeMimeSource).createMessage(100 - i);
messages.add(message);
}
await firstMimeSource.getMessage(0);
await firstMimeSource.resyncMessagesManually(messages);
expect(firstMimeSource.size, 99);
expect(source.size, 119);
expect(notifyCounter, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
// previous first message should now be at the second position:
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 19);
expect(message.mimeMessage.guid, 19);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 19');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.subtract(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
await expectMessagesOrderedByDate();
});
test('1 message added flag after resync', () async {
var sourceNotifyCounter = 0;
source.addListener(() {
sourceNotifyCounter++;
});
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await firstMimeSource.getMessage(i);
messages.add(message);
}
final copy = (firstMimeSource as FakeMimeSource)
.createMessage(messages[1].sequenceId ?? 0)
..isSeen = true;
messages[1] = copy;
var message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, copy.sequenceId);
expect(message.isSeen, isFalse);
var messageNotifyCounter = 0;
message.addListener(() {
messageNotifyCounter++;
});
await firstMimeSource.resyncMessagesManually(messages);
expect(source.size, 120);
expect(sourceNotifyCounter, 0);
expect(messageNotifyCounter, 1);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, copy.sequenceId);
expect(message.isSeen, isTrue);
await expectMessagesOrderedByDate();
});
test('1 message removed flag after resync', () async {
var sourceNotifyCounter = 0;
source.addListener(() {
sourceNotifyCounter++;
});
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await firstMimeSource.getMessage(i);
messages.add(message);
}
messages[1].isSeen = true;
final copy = (firstMimeSource as FakeMimeSource)
.createMessage(messages[1].sequenceId ?? 0);
messages[1] = copy;
var message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, copy.sequenceId);
expect(message.isSeen, isTrue);
var messageNotifyCounter = 0;
message.addListener(() {
messageNotifyCounter++;
});
await firstMimeSource.resyncMessagesManually(messages);
expect(source.size, 120);
expect(sourceNotifyCounter, 0);
expect(messageNotifyCounter, 1);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, copy.sequenceId);
expect(message.isSeen, isFalse);
await expectMessagesOrderedByDate();
});
test('1 message added, 1 removed, 1 changed flags after resync', () async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(2);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 99');
final messages = <MimeMessage>[];
for (int i = 0; i < 21; i++) {
final message =
(firstMimeSource as FakeMimeSource).createMessage(101 - i);
messages.add(message);
}
// remove 'firstSubject 100':
messages.removeAt(1);
// set 'firstSubject 99' to seen:
messages[1].isSeen = true;
await firstMimeSource.getMessage(0);
await firstMimeSource.resyncMessagesManually(messages);
expect(source.size, 120);
expect(notifyCounter, 2);
message = await source.getMessageAt(0);
expect(
message.mimeMessage.guid,
101,
reason: 'first message should be the 101',
);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(message.isSeen, isFalse);
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
// previous first message should now be at the second position:
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
expect(message.isSeen, isFalse);
message = await source.getMessageAt(2);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 99');
expect(message.isSeen, isTrue);
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.subtract(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
message = await source.getMessageAt(3);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 19');
expect(message.isSeen, isFalse);
await expectMessagesOrderedByDate();
});
test(
'1 message added ordered by date on each source after resync',
() async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
var messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message =
(firstMimeSource as FakeMimeSource).createMessage(101 - i);
messages.add(message);
}
await firstMimeSource.resyncMessagesManually(messages);
messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message =
(secondMimeSource as FakeMimeSource).createMessage(21 - i);
messages.add(message);
}
await secondMimeSource.resyncMessagesManually(messages);
expect(source.size, 122);
expect(notifyCounter, 2);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 21);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 21');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.add(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
expect(message.isSeen, isFalse);
// previous first message should now be at the second position:
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 101);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
message = await source.getMessageAt(2);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
await expectMessagesOrderedByDate();
},
);
test(
'1 message added unordered by date on each source after resync',
() async {
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
var messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message =
(secondMimeSource as FakeMimeSource).createMessage(21 - i);
messages.add(message);
}
await secondMimeSource.resyncMessagesManually(messages);
messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message =
(firstMimeSource as FakeMimeSource).createMessage(101 - i);
messages.add(message);
}
await firstMimeSource.resyncMessagesManually(messages);
expect(source.size, 122);
expect(notifyCounter, 2);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 21);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 21');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.add(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
expect(message.isSeen, isFalse);
// previous first message should now be at the second position:
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 101);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
message = await source.getMessageAt(2);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
await expectMessagesOrderedByDate();
},
);
test(
'out of cache: 1 message added, 2 removed, 2 changed flags after resync',
() async {
firstMimeSource = FakeMimeSource(
size: 100,
name: 'first',
startDate: firstMimeSourceStartDate,
differencePerMessage: firstMimeSourceDifferencePerMessage,
maxCacheSize: 20,
);
secondMimeSource = FakeMimeSource(
size: 20,
name: 'second',
startDate: secondMimeSourceStartDate,
differencePerMessage: secondMimeSourceDifferencePerMessage,
);
source = MultipleMessageSource(
[firstMimeSource, secondMimeSource],
'multiple',
MailboxFlag.inbox,
account: MockUnifiedAccount(),
);
var notifyCounter = 0;
source.addListener(() {
notifyCounter++;
});
// ensure caches are initialized across mime and message sources:
var message = await source.getMessageAt(0);
message.isSeen = true;
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
// create test messages:
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
await firstMimeSource.getMessage(i);
final message =
(firstMimeSource as FakeMimeSource).createMessage(100 - i);
messages.add(message);
}
// as this is out of cache, simulate changes by also these changes
// to the underlying structure:
messages[2].isAnswered = true;
messages
..removeAt(3)
..removeAt(7)
..insert(
0,
(firstMimeSource as FakeMimeSource).createMessage(101),
);
final serverMessages = FakeMimeSource.generateMessages(size: 99);
for (int i = 0; i < messages.length; i++) {
final message = messages[i]..sequenceId = 99 - i;
serverMessages[98 - i] = message;
}
// resync: ensure to remove first message from cache:
await firstMimeSource.getMessage(21);
await firstMimeSource.resyncMessagesManually(messages);
(firstMimeSource as FakeMimeSource).messages = serverMessages;
expect(source.size, 119);
expect(notifyCounter, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 99);
expect(message.mimeMessage.guid, 101);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 101');
expect(message.isSeen, isFalse);
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.add(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
// previous first message should now be at the second position:
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
expect(message.isSeen, isTrue);
message = await source.getMessageAt(2);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(message.isSeen, isFalse);
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
await expectMessagesOrderedByDate();
},
);
});
group('delete', () {
test('delete 1 message', () async {
notificationService.reset();
var sourceNotifyCounter = 0;
source.addListener(() {
sourceNotifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 99);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 99');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.subtract(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 19);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 19');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.subtract(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
final messages = [await source.getMessageAt(2)];
expect(source.size, 120);
await source.deleteMessages(
AppLocalizationsEn(),
messages,
'deleted messages',
);
expect(source.size, 119);
expect(sourceNotifyCounter, 1);
expect(notificationService.sendNotifications, 0);
expect(notificationService.cancelledNotifications, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 99);
expect(message.mimeMessage.guid, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 19);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 19');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.subtract(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
await expectMessagesOrderedByDate();
});
test('delete 1 message and clear cache', () async {
notificationService.reset();
var sourceNotifyCounter = 0;
source.addListener(() {
sourceNotifyCounter++;
});
var message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 99);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 99');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate
.subtract(firstMimeSourceDifferencePerMessage)
.toLocal(),
);
message = await source.getMessageAt(3);
expect(message.mimeMessage.sequenceId, 19);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 19');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.subtract(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
final messages = [await source.getMessageAt(2)];
expect(source.size, 120);
await source.deleteMessages(
AppLocalizationsEn(),
messages,
'deleted messages',
);
source.cache.clear();
expect(source.size, 119);
expect(sourceNotifyCounter, 1);
expect(notificationService.sendNotifications, 0);
expect(notificationService.cancelledNotifications, 1);
message = await source.getMessageAt(0);
expect(message.mimeMessage.sequenceId, 20);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 20');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(1);
expect(message.mimeMessage.sequenceId, 99);
expect(message.mimeMessage.guid, 100);
expect(message.mimeMessage.decodeSubject(), 'firstSubject 100');
expect(
message.mimeMessage.decodeDate(),
firstMimeSourceStartDate.toLocal(),
);
message = await source.getMessageAt(2);
expect(message.mimeMessage.sequenceId, 19);
expect(message.mimeMessage.decodeSubject(), 'secondSubject 19');
expect(
message.mimeMessage.decodeDate(),
secondMimeSourceStartDate
.subtract(secondMimeSourceDifferencePerMessage)
.toLocal(),
);
await expectMessagesOrderedByDate();
});
});
}
class TestScaffoldMessengerService implements ScaffoldMessengerService {
@override
void popStatusBarState() {
// TODO(RV): implement popStatusBarState
}
@override
// TODO(RV): implement scaffoldMessengerKey
GlobalKey<ScaffoldMessengerState> get scaffoldMessengerKey =>
throw UnimplementedError();
@override
void showTextSnackBar(
AppLocalizations localization,
String text, {
Function()? undo,
}) {
// TODO(RV): implement showTextSnackBar
}
@override
set statusBarState(CupertinoStatusBarState state) {
// TODO(RV): implement statusBarState
}
}
class TestNotificationService implements NotificationService {
int _cancelledNotifications = 0;
int get cancelledNotifications => _cancelledNotifications;
int _sendNotifications = 0;
int get sendNotifications => _sendNotifications;
void reset() {
_sendNotifications = 0;
_cancelledNotifications = 0;
}
@override
void cancelNotification(int id) {
_cancelledNotifications++;
}
@override
void cancelNotificationForMime(MimeMessage mimeMessage) {
_cancelledNotifications++;
}
@override
void cancelNotificationForMessage(Message message) {
_cancelledNotifications++;
}
@override
Future<List<MailNotificationPayload>> getActiveMailNotifications() {
// TODO(RV): implement getActiveMailNotifications
throw UnimplementedError();
}
@override
Future<NotificationServiceInitResult> init({
bool checkForLaunchDetails = true,
BuildContext? context,
}) {
// TODO(RV): implement init
throw UnimplementedError();
}
@override
Future sendLocalNotificationForMail(
MimeMessage mimeMessage,
String accountEmail,
) {
_sendNotifications++;
return Future.value();
}
@override
Future sendLocalNotificationForMailLoadEvent(MailLoadEvent event) =>
sendLocalNotificationForMail(
event.message,
event.mailClient.account.email,
);
@override
Future sendLocalNotificationForMailMessage(Message message) {
_sendNotifications++;
return Future.value();
}
}
| 0
|
mirrored_repositories/enough_mail_app/test
|
mirrored_repositories/enough_mail_app/test/model/fake_mime_source.dart
|
import 'dart:math';
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_mail_app/src/models/async_mime_source.dart';
class FakeMimeSource extends PagedCachedMimeSource {
FakeMimeSource({
required int size,
super.maxCacheSize,
this.name = '',
DateTime? startDate,
Duration? differencePerMessage,
}) : _startDate = startDate ?? DateTime(2022, 04, 16, 08),
_differencePerMessage =
differencePerMessage ?? const Duration(minutes: 5),
mailClient = MailClient(
MailAccount.fromManualSettings(
name: name,
email: 'test@domain.com',
incomingHost: 'imap.domain.com',
outgoingHost: 'smtp.domain.com',
password: 'password',
),
) {
messages = generateMessages(
size: size,
name: name,
startDate: _startDate,
differencePerMessage: _differencePerMessage,
);
}
final DateTime _startDate;
final Duration _differencePerMessage;
List<MimeMessage> messages = [];
static List<MimeMessage> generateMessages({
required int size,
String name = '',
DateTime? startDate,
Duration? differencePerMessage,
}) {
final messages = <MimeMessage>[];
for (int i = size; --i >= 0;) {
messages.add(
_generateMessage(
size - i,
size,
name,
startDate ?? DateTime(2022, 04, 16, 08),
differencePerMessage ?? const Duration(minutes: 5),
),
);
}
return messages;
}
static MimeMessage _generateMessage(
int sequenceId,
int size,
String name,
DateTime startDate,
Duration differencePerMessage,
) =>
MimeMessage()
..sequenceId = sequenceId
..guid = sequenceId
..uid = sequenceId
..addHeader(MailConventions.headerSubject, '${name}Subject $sequenceId')
..addHeader(
MailConventions.headerDate,
DateCodec.encodeDate(_generateDate(
size - sequenceId,
startDate,
differencePerMessage,
)),
);
static DateTime _generateDate(
int index,
DateTime startDate,
Duration differencePerMessage,
) =>
startDate.subtract(differencePerMessage * index);
MimeMessage createMessage(int sequenceId) => _generateMessage(
sequenceId,
size,
name,
_startDate,
_differencePerMessage,
);
@override
final String name;
@override
int get size => messages.length;
final _random = Random();
@override
Future<DeleteResult> deleteMessages(List<MimeMessage> messages) {
messages.sort((a, b) => (b.sequenceId ?? 0).compareTo(a.sequenceId ?? 0));
for (final message in messages) {
final sequenceId = message.sequenceId ?? -1;
this.messages.removeAt(sequenceId - 1);
for (var i = sequenceId - 1; i < this.messages.length; i++) {
this.messages[i].sequenceId = i + 1;
}
}
return Future.value(
DeleteResult(
DeleteAction.flag,
messages.toSequence(),
Mailbox(
encodedName: 'INBOX',
encodedPath: 'INBOX',
flags: [MailboxFlag.inbox],
pathSeparator: '/',
),
null,
null,
mailClient,
canUndo: false,
),
);
}
@override
Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) async {
await Future.delayed(Duration(milliseconds: _random.nextInt(1000)));
messages.clear();
clear();
final sequence = MessageSequence.fromAll();
final mailbox = Mailbox(
encodedName: 'INBOX',
encodedPath: 'INBOX',
flags: [MailboxFlag.inbox],
pathSeparator: '/',
);
return [
DeleteResult(
DeleteAction.flag,
sequence,
mailbox,
sequence,
mailbox,
mailClient,
canUndo: false,
),
];
}
@override
Future<void> init() => Future.value();
@override
// TODO(RV): implement isArchive
bool get isArchive => throw UnimplementedError();
@override
// TODO(RV): implement isJunk
bool get isJunk => throw UnimplementedError();
@override
// TODO(RV): implement isSent
bool get isSent => throw UnimplementedError();
@override
// TODO(RV): implement isTrash
bool get isTrash => throw UnimplementedError();
@override
Future<List<MimeMessage>> loadMessages(MessageSequence sequence) async {
await Future.delayed(Duration(milliseconds: _random.nextInt(200)));
final indices = sequence.toList(size);
final result = <MimeMessage>[];
for (final index in indices) {
final message = messages[index - 1];
result.add(message);
}
return result;
}
Future<void> addFakeMessage(int sequenceId) =>
onMessageArrived(createMessage(sequenceId));
@override
Future<void> handleOnMessageArrived(int index, MimeMessage message) async {
messages.add(message);
}
@override
Future<void> handleOnMessagesVanished(List<MimeMessage> removed) async {
removed.forEach(messages.remove);
}
@override
AsyncMimeSource search(MailSearch search) {
// TODO(RV): implement search
throw UnimplementedError();
}
@override
bool get supportsDeleteAll => true;
@override
// TODO(RV): implement supportsMessageFolders
bool get supportsMessageFolders => throw UnimplementedError();
@override
// TODO(RV): implement supportsSearching
bool get supportsSearching => throw UnimplementedError();
@override
void dispose() {
// TODO(RV): implement dispose
}
@override
final MailClient mailClient;
@override
Future<void> store(
List<MimeMessage> messages,
List<String> flags, {
StoreAction action = StoreAction.add,
}) {
// TODO(RV): implement store
throw UnimplementedError();
}
@override
Future<void> storeAll(
List<String> flags, {
StoreAction action = StoreAction.add,
}) {
// TODO(RV): implement storeAll
throw UnimplementedError();
}
@override
Future<DeleteResult> undoDeleteMessages(DeleteResult deleteResult) {
// TODO(RV): implement undoDeleteMessages
throw UnimplementedError();
}
@override
Future<MoveResult> moveMessages(
List<MimeMessage> messages,
Mailbox targetMailbox,
) {
// TODO(RV): implement moveMessages
throw UnimplementedError();
}
@override
Future<MoveResult> moveMessagesToFlag(
List<MimeMessage> messages,
MailboxFlag targetMailboxFlag,
) {
// TODO(RV): implement moveMessagesToFlag
throw UnimplementedError();
}
@override
Future<MoveResult> undoMoveMessages(MoveResult moveResult) {
// TODO(RV): implement undoMoveMessages
throw UnimplementedError();
}
@override
Future<MimeMessage> fetchMessageContents(
MimeMessage message, {
int? maxSize,
bool markAsSeen = false,
List<MediaToptype>? includedInlineTypes,
Duration? responseTimeout,
}) {
// TODO(RV): implement fetchMessageContents
throw UnimplementedError();
}
@override
// TODO(RV): implement isInbox
bool get isInbox => throw UnimplementedError();
@override
Future<MimePart> fetchMessagePart(
MimeMessage message, {
required String fetchId,
Duration? responseTimeout,
}) {
// TODO(RV): implement fetchMessagePart
throw UnimplementedError();
}
@override
Future<void> sendMessage(
MimeMessage message, {
MailAddress? from,
bool appendToSent = true,
Mailbox? sentMailbox,
bool use8BitEncoding = false,
List<MailAddress>? recipients,
}) {
// TODO(RV): implement sendMessage
throw UnimplementedError();
}
@override
// TODO(RV): implement mailbox
Mailbox get mailbox => throw UnimplementedError();
}
| 0
|
mirrored_repositories/enough_mail_app/test
|
mirrored_repositories/enough_mail_app/test/model/async_mime_source_test.dart
|
// ignore_for_file: lines_longer_than_80_chars
import 'package:enough_mail/enough_mail.dart';
import 'package:enough_mail_app/src/models/async_mime_source.dart';
import 'package:flutter_test/flutter_test.dart';
import 'fake_mime_source.dart';
void main() async {
test('load first message size 100', () async {
final AsyncMimeSource source = FakeMimeSource(size: 100);
expect(source.size, 100);
final message = await source.getMessage(0);
expect(message.sequenceId, 100);
expect(message.decodeSubject(), 'Subject 100');
});
test('load first message size 101', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
expect(source.size, 101);
final message = await source.getMessage(0);
expect(message.sequenceId, 101);
expect(message.decodeSubject(), 'Subject 101');
});
test('load first message from cache size 101', () async {
final source = FakeMimeSource(size: 101);
expect(source.size, 101);
await source.getMessage(0);
final message = source.cache[0];
expect(message, isNotNull);
expect(message?.sequenceId, 101);
expect(message?.decodeSubject(), 'Subject 101');
});
test('load second message size 101', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
expect(source.size, 101);
final message = await source.getMessage(1);
expect(message.sequenceId, 100);
expect(message.decodeSubject(), 'Subject 100');
});
test('load several messages at once', () async {
final CachedMimeSource source = FakeMimeSource(size: 101);
expect(source.size, 101);
final futures = <Future<MimeMessage>>[];
for (int i = 0; i < 101; i += 15) {
final future = source.getMessage(i);
futures.add(future);
}
await Future.wait(futures);
final cache = source.cache;
for (int i = 0; i < 101; i += 15) {
final message = cache[i];
expect(message, isNotNull);
expect(message?.sequenceId, 101 - i);
}
});
test('load messages with small cache', () async {
final CachedMimeSource source = FakeMimeSource(size: 100, maxCacheSize: 10);
expect(source.size, 100);
for (int i = 0; i < 100; i += 7) {
final message = await source.getMessage(i);
expect(message.sequenceId, 100 - i);
}
});
test('load messages with small cache at cache border', () async {
final CachedMimeSource source = FakeMimeSource(size: 100, maxCacheSize: 10);
expect(source.size, 100);
for (int i = 1; i < 99; i += 10) {
var message = await source.getMessage(i - 1);
expect(message.sequenceId, 100 - (i - 1));
message = await source.getMessage(i);
expect(message.sequenceId, 100 - i);
message = await source.getMessage(i + 1);
expect(message.sequenceId, 100 - (i + 1));
}
});
test('load several messages at once with small cache', () async {
final CachedMimeSource source = FakeMimeSource(size: 101, maxCacheSize: 10);
expect(source.size, 101);
final futures = <Future<MimeMessage>>[];
final expectedSequenceIds = <int>[];
for (int i = 0; i < 101; i += 7) {
final future = source.getMessage(i);
futures.add(future);
expectedSequenceIds.add(101 - i);
}
final messages = await Future.wait(futures);
for (int i = 0; i < messages.length; i++) {
expect(
messages[i].sequenceId,
expectedSequenceIds[i],
reason: 'failed for index $i',
);
}
});
test('onMessageArrived', () async {
final source = FakeMimeSource(size: 101);
expect(source.size, 101);
await source.addFakeMessage(102);
expect(source.size, 102);
for (int i = 0; i < 102; i += 13) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 102 - i);
}
});
test('2 x onMessageArrived', () async {
final source = FakeMimeSource(size: 101);
expect(source.size, 101);
await source.addFakeMessage(102);
await source.addFakeMessage(103);
expect(source.size, 103);
for (int i = 0; i < 103; i += 13) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 103 - i);
}
});
test('onMessageArrived with old message', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final firstMessage = await source.getMessage(0);
final newMessage = source.createMessage(101);
final oldDate =
firstMessage.decodeDate()?.subtract(const Duration(seconds: 30)) ??
DateTime.now();
newMessage.setHeader(
MailConventions.headerDate,
DateCodec.encodeDate(oldDate),
);
await source.onMessageArrived(newMessage);
expect(source.size, 101);
var message = await source.getMessage(0);
expect(
message.sequenceId,
100,
reason: 'first message should stay the same',
);
message = await source.getMessage(1);
expect(
message.sequenceId,
101,
reason: 'second message should be the new message',
);
});
Future<void> expectMessagesOrderedByDate(
AsyncMimeSource source, {
int? numberToTest,
}) async {
var lastDate = DateTime.now();
var lastSubject = '<no message>';
final length = numberToTest ?? source.size;
for (int i = 0; i < length; i++) {
final message = await source.getMessage(i);
final messageDate = message.decodeDate() ?? DateTime.now();
final subject = message.decodeSubject() ?? '<no subject for $i>';
expect(
messageDate,
isNotNull,
reason: 'no date for message at index $i $subject',
);
expect(
messageDate.isBefore(lastDate),
isTrue,
reason:
'wrong date for message at $i: $messageDate of "$subject" should be before $lastDate of "$lastSubject"',
);
lastDate = messageDate;
lastSubject = subject;
}
}
test('init with old message in first result', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final firstMessage = source.messages[0];
final oldDate = firstMessage
.decodeDate()
?.subtract(const Duration(days: 120, seconds: 30));
source.messages[97].setHeader(
MailConventions.headerDate,
DateCodec.encodeDate(
oldDate ?? DateTime.now(),
),
);
// first page should be sorted:
await expectMessagesOrderedByDate(source, numberToTest: 20);
});
test('onMessagesVanished - sequence IDs', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
Future<void> expectMessage(
int index,
int expectedGuid, [
String? reason,
]) async {
final message = await source.getMessage(index);
expect(message.guid, expectedGuid, reason: reason);
}
expect(source.size, 101);
// cache all messages:
for (int i = 0; i < 101; i += 3) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 101 - i);
}
await source.onMessagesVanished(MessageSequence.fromIds([101, 99, 98]));
expect(source.size, 98, reason: '3 messages should be removed');
await expectMessage(0, 100, 'first message expected to be 100');
await expectMessage(1, 97, 'second message should be 97');
for (int i = 2; i < 98; i += 7) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 98 - i);
}
});
test('onMessagesVanished - latest message', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
Future<void> expectMessage(int index, int expectedSequenceId) async {
final message = await source.getMessage(index);
expect(message.sequenceId, expectedSequenceId);
}
expect(source.size, 101);
// cache all messages:
for (int i = 0; i < 101; i += 3) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 101 - i);
}
await source.onMessagesVanished(MessageSequence.fromIds([101]));
expect(source.size, 100);
await expectMessage(0, 100);
await expectMessage(1, 99);
for (int i = 2; i < 100; i += 7) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 100 - i);
}
});
test('onMessagesVanished - same valid sequence ID twice', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
Future<void> expectMessage(
int index,
int expectedSequenceId, [
String? reason,
]) async {
final message = await source.getMessage(index);
expect(message.sequenceId, expectedSequenceId, reason: reason);
}
expect(source.size, 101);
// cache all messages:
for (int i = 0; i < 101; i += 3) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 101 - i);
}
await source.onMessagesVanished(MessageSequence.fromIds([100]));
expect(source.size, 100);
await expectMessage(
0,
100,
"first message's sequence ID should be adapted",
);
await expectMessage(1, 99);
await source.onMessagesVanished(MessageSequence.fromIds([100]));
expect(source.size, 99);
await expectMessage(0, 99);
await expectMessage(1, 98);
for (int i = 2; i < 99; i += 7) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 99 - i);
}
});
test('onMessagesVanished - sequence IDs reverse', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
Future<void> expectMessage(
int index,
int expectedGuid, [
String? reason,
]) async {
final message = await source.getMessage(index);
expect(message.guid, expectedGuid, reason: reason);
}
expect(source.size, 101);
// cache all messages:
for (int i = 0; i < 101; i += 3) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 101 - i);
}
await source.onMessagesVanished(MessageSequence.fromIds([98, 99, 101]));
expect(source.size, 98);
await expectMessage(0, 100, 'first message should be 100');
await expectMessage(1, 97, 'second message should be 97');
for (int i = 2; i < 98; i += 7) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 98 - i);
}
});
test('onMessagesVanished - UIDs', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
Future<void> expectMessage(
int index,
int expectedGuid, [
String? reason,
]) async {
final message = await source.getMessage(index);
expect(message.guid, expectedGuid, reason: reason);
}
expect(source.size, 101);
// cache all messages:
for (int i = 0; i < 101; i += 3) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 101 - i);
}
await source.onMessagesVanished(
MessageSequence.fromIds([101, 99, 98], isUid: true),
);
expect(source.size, 98);
await expectMessage(0, 100, 'first should be 100');
await expectMessage(1, 97, 'second should be 97');
for (int i = 2; i < 98; i += 7) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 98 - i);
}
});
test('onMessagesVanished - UIDs reversed', () async {
final AsyncMimeSource source = FakeMimeSource(size: 101);
Future<void> expectMessage(
int index,
int expectedGuid, [
String? reason,
]) async {
final message = await source.getMessage(index);
expect(message.guid, expectedGuid, reason: reason);
}
expect(source.size, 101);
// cache all messages:
for (int i = 0; i < 101; i += 3) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 101 - i);
}
await source.onMessagesVanished(
MessageSequence.fromIds([98, 99, 101], isUid: true),
);
expect(source.size, 98);
await expectMessage(0, 100, 'first should be 100');
await expectMessage(1, 97, 'second should be 97');
for (int i = 2; i < 98; i += 7) {
final message = await source.getMessage(i);
expect(message, isNotNull);
expect(message.sequenceId, 98 - i);
}
});
group('resync manually', () {
test('same messages after resync', () async {
final AsyncMimeSource source = FakeMimeSource(size: 100);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
messages.add(message);
}
expect(source.size, 100);
await source.resyncMessagesManually(messages);
expect(source.size, 100);
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
}
});
test('same re-created messages after resync', () async {
final source = FakeMimeSource(size: 100);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = source.createMessage(100 - i);
messages.add(message);
}
expect(source.size, 100);
await source.resyncMessagesManually(messages);
expect(source.size, 100);
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
}
});
test('1 new message after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
messages.add(message);
}
expect(source.size, 100);
messages.insert(0, source.createMessage(101));
await source.resyncMessagesManually(messages);
expect(source.size, 101);
for (int i = 0; i < 21; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
}
});
test('1 removed message after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
messages.add(message);
}
messages.removeAt(1);
await source.resyncMessagesManually(messages);
expect(source.size, 99);
for (int i = 0; i < 19; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
}
});
test('1 message added flag after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
messages.add(message);
}
final copy = source.createMessage(messages[1].sequenceId ?? -1)
..isSeen = true;
messages[1] = copy;
await source.resyncMessagesManually(messages);
expect(source.size, 100);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
});
test('1 message removed flag after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
if (i == 1) {
message.isSeen = true;
}
messages.add(message);
}
final copy = source.createMessage(messages[1].sequenceId ?? -1);
messages[1] = copy;
await source.resyncMessagesManually(messages);
expect(source.size, 100);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
});
test('1 message added, 1 removed, 1 changed flags after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
messages.add(message);
}
final copy = source.createMessage(messages[1].sequenceId ?? -1)
..isSeen = true;
messages[1] = copy;
messages.removeAt(2);
final newMessage = source.createMessage(101);
messages.insert(0, newMessage);
await source.resyncMessagesManually(messages);
expect(source.size, 100);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
});
test('2 new message after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
// ensure first message is loaded and cached:
await source.getMessage(0);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = source.createMessage(102 - i);
messages.add(message);
}
await source.resyncMessagesManually(messages);
expect(source.size, 102);
for (int i = 0; i < 20; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
}
});
test('2 removed messages after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
// ensure first message is loaded and cached:
await source.getMessage(0);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = source.createMessage(100 - i);
messages.add(message);
}
messages
..removeAt(1)
..removeAt(2);
await source.resyncMessagesManually(messages);
expect(source.size, 98);
for (int i = 0; i < 18; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
}
});
test('2 messages changed flags after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final seen = await source.getMessage(1);
seen.isSeen = true;
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = source.createMessage(100 - i);
messages.add(message);
}
messages[2].isAnswered = true;
await source.resyncMessagesManually(messages);
expect(source.size, 100);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
});
test('2 message added, 2 removed, 2 changed flags after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final seen = await source.getMessage(1);
seen.isSeen = true;
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = source.createMessage(100 - i);
messages.add(message);
}
messages[2].isAnswered = true;
messages
..removeAt(3)
..removeAt(7)
..insert(0, source.createMessage(101))
..insert(0, source.createMessage(102));
await source.resyncMessagesManually(messages);
expect(source.size, 100);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
});
test('1 message added, 2 removed, 2 changed flags after resync', () async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final seen = await source.getMessage(1);
seen.isSeen = true;
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = source.createMessage(100 - i);
messages.add(message);
}
messages[2].isAnswered = true;
messages
..removeAt(3)
..removeAt(7)
..insert(0, source.createMessage(101));
await source.resyncMessagesManually(messages);
expect(source.size, 99);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
});
test(
'out of cache: 1 message added, 2 removed, 2 changed flags after resync',
() async {
final source = FakeMimeSource(size: 100, maxCacheSize: 20);
expect(source.size, 100);
final seen = await source.getMessage(1);
seen.isSeen = true;
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
await source.getMessage(i);
final message = source.createMessage(100 - i);
messages.add(message);
}
// as this is out of cache, simulate changes by also these changes
// to the underlying structure:
messages[2].isAnswered = true;
messages
..removeAt(3)
..removeAt(7)
..insert(0, source.createMessage(101));
final serverMessages = FakeMimeSource.generateMessages(size: 99);
for (int i = 0; i < messages.length; i++) {
final message = messages[i]..sequenceId = 99 - i;
serverMessages[98 - i] = message;
}
// resync: ensure to remove first message from cache:
await source.getMessage(21);
await source.resyncMessagesManually(messages);
source.messages = serverMessages;
expect(source.size, 99);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid GUID ${message.guid} at $i',
);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
},
);
test(
'delete 1 message, then 1 message added, 2 removed, 2 changed flags after resync',
() async {
final source = FakeMimeSource(size: 100);
expect(source.size, 100);
final seenMessage = await source.getMessage(1);
seenMessage.isSeen = true;
final deleteMessage = await source.getMessage(2);
await source.deleteMessages([deleteMessage]);
expect(source.size, 99);
final firstMessage = await source.getMessage(0);
expect(firstMessage.sequenceId, 99);
final messages = <MimeMessage>[];
for (int i = 0; i < 20; i++) {
final message = source.createMessage(100 - i)..sequenceId = 99 - i;
messages.add(message);
}
messages[2].isAnswered = true;
messages
..removeAt(3)
..removeAt(7)
..insert(0, source.createMessage(101));
await source.resyncMessagesManually(messages);
expect(source.size, 98);
for (int i = 0; i < messages.length; i++) {
final message = await source.getMessage(i);
expect(
message.guid,
messages[i].guid,
reason: 'invalid message ${message.guid} at $i',
);
expect(
message.flags,
messages[i].flags,
reason: 'flags differ for message ${message.guid} at $i',
);
}
},
);
});
}
| 0
|
mirrored_repositories/enough_mail_app/test
|
mirrored_repositories/enough_mail_app/test/util/indexed_cache_test.dart
|
import 'package:enough_mail_app/src/util/indexed_cache.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('add entries', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], 'c');
expect(cache[3], 'd');
});
test('add entries reverse', () {
final cache = IndexedCache<String>();
cache[3] = 'd';
cache[2] = 'c';
cache[1] = 'b';
cache[0] = 'a';
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], 'c');
expect(cache[3], 'd');
});
test('insert entries at 0', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.insert(0, 'x');
expect(cache[1], 'a');
expect(cache[2], 'b');
expect(cache[3], 'c');
expect(cache[4], 'd');
expect(cache[0], 'x');
cache.insert(0, 'y');
expect(cache[2], 'a');
expect(cache[3], 'b');
expect(cache[4], 'c');
expect(cache[5], 'd');
expect(cache[1], 'x');
expect(cache[0], 'y');
});
test('insert entries at 1', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.insert(1, 'x');
expect(cache[0], 'a');
expect(cache[1], 'x');
expect(cache[2], 'b');
expect(cache[3], 'c');
expect(cache[4], 'd');
cache.insert(1, 'y');
expect(cache[0], 'a');
expect(cache[1], 'y');
expect(cache[2], 'x');
expect(cache[3], 'b');
expect(cache[4], 'c');
expect(cache[5], 'd');
});
test('removeAt 2', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.removeAt(2);
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], 'd');
expect(cache[3], isNull);
cache.removeAt(2);
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], isNull);
expect(cache[3], isNull);
});
test('removeAt 0', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.removeAt(0);
expect(cache[0], 'b');
expect(cache[1], 'c');
expect(cache[2], 'd');
expect(cache[3], isNull);
cache.removeAt(0);
expect(cache[0], 'c');
expect(cache[1], 'd');
expect(cache[2], isNull);
expect(cache[3], isNull);
});
test('removeAt 500', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.removeAt(500);
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], 'c');
expect(cache[3], 'd');
});
test('remove', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.remove('c');
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], 'd');
expect(cache[3], isNull);
cache.remove('d');
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], isNull);
expect(cache[3], isNull);
});
test('removeFirstWhere c, d', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.removeFirstWhere((element) => element == 'c');
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], 'd');
expect(cache[3], isNull);
cache.removeFirstWhere((element) => element == 'd');
expect(cache[0], 'a');
expect(cache[1], 'b');
expect(cache[2], isNull);
expect(cache[3], isNull);
});
test('removeFirstWhere a, b', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.removeFirstWhere((element) => element == 'a');
expect(cache[0], 'b');
expect(cache[1], 'c');
expect(cache[2], 'd');
expect(cache[3], isNull);
cache.removeFirstWhere((element) => element == 'b');
expect(cache[0], 'c');
expect(cache[1], 'd');
expect(cache[2], isNull);
expect(cache[3], isNull);
});
test('clear', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache.clear();
expect(cache[0], isNull);
expect(cache[1], isNull);
expect(cache[2], isNull);
expect(cache[3], isNull);
});
test('getAllCachedEntries', () {
final cache = IndexedCache<String>();
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
expect(cache.getAllCachedEntries(), ['a', 'b', 'c', 'd']);
});
test('shrink cache after adding element', () {
final cache = IndexedCache<String>(maxCacheSize: 4);
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache[4] = 'e';
expect(cache.getAllCachedEntries(), ['b', 'c', 'd', 'e']);
expect(cache[0], isNull);
});
test('shrink cache after adding element twice', () {
final cache = IndexedCache<String>(maxCacheSize: 4);
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache[4] = 'e';
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache[4] = 'e';
expect(cache.getAllCachedEntries(), ['b', 'c', 'd', 'e']);
expect(cache[0], isNull);
});
test('shrink cache after re-setting first element', () {
final cache = IndexedCache<String>(maxCacheSize: 4);
cache[0] = 'a';
cache[1] = 'b';
cache[2] = 'c';
cache[3] = 'd';
cache[4] = 'e';
cache[0] = 'a';
expect(cache.getAllCachedEntries(), ['a', 'c', 'd', 'e']);
expect(cache[1], isNull);
});
test('forEachWhere', () {
final cache = IndexedCache<_Entry>();
cache[0] = _Entry('a', 0);
cache[1] = _Entry('b', 1);
cache[2] = _Entry('c', 2);
cache[3] = _Entry('d', 3);
cache[4] = _Entry('e', 4);
cache.forEachWhere((e) => e.index >= 3, (e) => e.index++);
expect(cache[0]?.index, 0);
expect(cache[1]?.index, 1);
expect(cache[2]?.index, 2);
expect(cache[3]?.index, 4);
expect(cache[4]?.index, 5);
});
}
class _Entry {
_Entry(this.text, this.index);
final String text;
int index;
}
| 0
|
mirrored_repositories/enough_mail_app
|
mirrored_repositories/enough_mail_app/tools/localization_extender.dart
|
/// This command line tool reads the localization arb files from a referenced
/// project and extends them with arb files from the current project.
/// It can additionally replace text-parts in the referenced arb files.
///
/// Input:
/// - The path to the referenced project, a l10n yaml configuration is expected
/// - The path to the current project, a l10n yaml configuration is expected
/// - One or more replace commands
///
/// Intermediate Output:
/// - The extended arb files in the current project
///
/// The tool then runs `flutter gen-l10n` to generate the dart files.
/// The tool then ensures compatibility of the generated localizations
/// classes with the referenced original classes by adding an
/// `implements $referencedProjectLocalizations` and a corresponding import
/// to the generated class.
library;
import 'dart:convert';
import 'dart:io';
// ignore_for_file: avoid_print
/// The main function of the tool
void main(List<String> arguments) {
final args = arguments.toList();
if (args.length < 3) {
print(
'Usage: localization_extender.dart '
'<referencedProjectPath> <currentProjectPath> '
'<currentProjectLocalizationPath> [replaceCommands]',
);
return;
}
String parseImportPackage(String path) {
String parsePackageWithSeparator(String path, String separator) {
final parts = path.split(separator);
if (path.endsWith(separator) && parts.length > 1) {
return parts[parts.length - 2];
}
return parts.last;
}
return path.contains(Platform.pathSeparator)
? parsePackageWithSeparator(path, Platform.pathSeparator)
: parsePackageWithSeparator(path, '/');
}
final referencedProjectPath = args.removeAt(0);
final currentProjectPath = args.removeAt(0);
final currentProjectLocalizationPath = args.removeAt(0);
final importPackage = parseImportPackage(referencedProjectPath);
final replaceCommands = args;
LocalizationExtender(
referencedProjectPath: referencedProjectPath,
currentProjectPath: currentProjectPath,
replaceCommands: replaceCommands,
importPackage: importPackage,
currentProjectLocalizationPath: currentProjectLocalizationPath,
).run();
}
/// The localization extender
class LocalizationExtender {
/// Creates a new localization extender
LocalizationExtender({
required this.referencedProjectPath,
required this.currentProjectPath,
required this.replaceCommands,
required this.importPackage,
required this.currentProjectLocalizationPath,
});
/// The path to the referenced project
final String referencedProjectPath;
/// The path to the current project
final String currentProjectPath;
/// The replace commands
final List<String> replaceCommands;
/// The path to the current project localization files
final String currentProjectLocalizationPath;
/// The package to be imported
final String importPackage;
/// Runs the localization extender
void run() {
final referencedProject = Project(referencedProjectPath);
final now = DateTime.now()
.toIso8601String()
.replaceAll(':', '_')
.replaceAll('.', '_');
final temporaryPath = '$currentProjectPath/build/tmp/$now';
final temporaryL10n = L10nYaml(
path: temporaryPath,
outputDir: 'localizations',
arbDir: 'localizations',
preferredSupportedLocales:
referencedProject.l10nYaml.preferredSupportedLocales,
templateArbFile: referencedProject.l10nYaml.templateArbFile,
outputLocalizationFile: referencedProject.l10nYaml.outputLocalizationFile,
outputClass: 'Custom${referencedProject.l10nYaml.outputClass}',
)..write();
final currentProject = Project(
currentProjectPath,
l10nYaml: temporaryL10n,
localDir: currentProjectLocalizationPath,
);
final extendedArbFiles = <String, Map<String, dynamic>>{};
// run the replace commands in the referenced ARB files:
for (final arbFile in referencedProject.arbFiles) {
final contents = arbFile.read();
extendedArbFiles[arbFile.name] = contents;
}
for (final replaceCommand in replaceCommands) {
final parts = replaceCommand.split('=');
if (parts.length != 2) {
print('Ignoring invalid replace command: $replaceCommand');
continue;
}
final match = parts[0];
final replacement = parts[1];
for (final arb in extendedArbFiles.values) {
replaceInArb(arb, match, replacement);
}
}
// extend the referenced arb files with the current project arb files:
for (final currentArbFile in currentProject.arbFiles) {
final referencedArbMap = extendedArbFiles[currentArbFile.name];
if (referencedArbMap == null) {
print('No referenced arb file found for ${currentArbFile.name}');
continue;
}
print('Extending ${currentArbFile.name}.');
extendArb(referencedArbMap, currentArbFile.read());
}
// write the extended arb files to the current project:
for (final entry in extendedArbFiles.entries) {
final referencedEntries = extendedArbFiles[entry.key];
if (referencedEntries == null) {
continue;
}
final arbFile = referencedProject.arbFilesByName[entry.key];
if (arbFile == null) {
print('No arb file found for ${entry.key}');
continue;
}
arbFile.writeTo('$temporaryPath/localizations', entry.value);
}
currentProject
..copyPubspecYaml(temporaryPath)
..runFlutterGenL10n(temporaryPath)
..ensureCompatibility(
temporaryPath: temporaryPath,
referencedProject: referencedProject,
importPackage: importPackage,
outputPath: currentProjectLocalizationPath,
);
}
/// Extends the arb file with the referenced arb file
void extendArb(
Map<String, dynamic> referencedArb,
Map<String, dynamic> extendingArb,
) {
referencedArb.addAll(extendingArb);
// for (final entry in extendingArb.entries) {
// final key = entry.key;
// final value = entry.value;
// referencedArb[key] = value;
// if (value is String) {
// final referencedValue = referencedArb[key];
// if (referencedValue is String) {
// extendedArb[key] = '$value\n$referencedValue';
// } else {
// extendedArb[key] = value;
// }
// } else if (value is Map<String, dynamic>) {
// final referencedValue = referencedArb[key];
// if (referencedValue is Map<String, dynamic>) {
// extendedArb[key] = extendArb(value, referencedValue);
// } else {
// extendedArb[key] = value;
// }
// } else {
// extendedArb[key] = value;
// }
// }
// return extendedArb;
}
/// Replaces the value in the arb file
void replaceInArb(
Map<String, dynamic> arb,
String match,
String replacement,
) {
for (final entry in arb.entries) {
final value = entry.value;
if (value is String) {
final replacedValue = value.replaceAll(match, replacement);
if (replacedValue != value) {
arb[entry.key] = replacedValue;
}
}
}
}
}
/// A project
class Project {
/// Creates a new project
Project(this.path, {L10nYaml? l10nYaml, String? localDir}) {
_load(l10nYaml, localDir);
}
/// The path to the project
final String path;
final _arbFilesByName = <String, ArbFile>{};
final _arbFiles = <ArbFile>[];
late final L10nYaml l10nYaml;
/// The arb files of the project
Map<String, ArbFile> get arbFilesByName => _arbFilesByName;
List<ArbFile> get arbFiles => _arbFiles;
/// Loads the project and resolves the arb files
void _load(L10nYaml? givenL10nYaml, String? localDir) {
// Load the l10n.yaml file:
l10nYaml = givenL10nYaml ?? L10nYaml.fromPath(path);
// load the arb files:
final usedLocalDir = localDir ?? '$path/${l10nYaml.arbDir}';
final dir = Directory(usedLocalDir);
final files = dir.listSync();
for (final file in files) {
if (file is File && file.path.endsWith('.arb')) {
final arbFile = ArbFile(file.path);
_arbFilesByName[arbFile.name] = arbFile;
_arbFiles.add(arbFile);
print('Processing: $usedLocalDir/${arbFile.name}');
}
}
}
/// Runs `flutter gen-l10n`
void runFlutterGenL10n(String path) {
final process = Process.runSync(
'flutter',
[
'gen-l10n',
],
workingDirectory: path,
runInShell: true,
);
if (process.exitCode != 0) {
print(process.stdout);
print(process.stderr);
}
}
/// Ensures compatibility with the referenced project
void ensureCompatibility({
required String temporaryPath,
required Project referencedProject,
required String importPackage,
required String outputPath,
}) {
final referencedProjectLocalizations =
referencedProject.l10nYaml.outputClass;
final dir = Directory('$temporaryPath/localizations');
final files = dir.listSync(recursive: true);
final generatedFiles =
files.where((f) => f is File && f.path.endsWith('.g.dart')).toList();
void writeFileToOutputDir(File file, String content) {
File('$outputPath/${file.name}').writeAsStringSync(content);
}
for (final file in generatedFiles) {
if (file is! File) {
continue;
}
final content = file.readAsStringSync();
if (!content.contains('abstract class ${l10nYaml.outputClass}')) {
writeFileToOutputDir(file, content);
}
final import = "import 'package:$importPackage/$importPackage.dart';\n";
final newContent = import +
content.replaceFirst(
'abstract class ${l10nYaml.outputClass}',
'abstract class ${l10nYaml.outputClass} '
'implements $referencedProjectLocalizations',
);
writeFileToOutputDir(file, newContent);
}
}
/// Copies the pubspec.yaml file
void copyPubspecYaml(String temporaryPath) {
final file = File('$path/pubspec.yaml');
final content = file.readAsStringSync();
File('$temporaryPath/pubspec.yaml').writeAsStringSync(content);
}
}
/// An arb file
class ArbFile {
/// Creates a new arb file
ArbFile(this.path);
/// The path to the arb file
final String path;
/// The name of the arb file
String get name {
final parts = path.split(Platform.pathSeparator);
return parts.last;
}
/// Reads the arb file
Map<String, dynamic> read() {
final file = File(path);
final content = file.readAsStringSync();
return _arbToJson(content);
}
/// Writes the arb file
void write(Map<String, dynamic> arb) {
final file = File(path);
final content = _jsonToArb(arb);
file.writeAsStringSync(content);
}
/// Converts arb to json
Map<String, dynamic> _arbToJson(String arb) => jsonDecode(arb);
/// Converts json to arb
String _jsonToArb(Map<String, dynamic> json) => _prettyPrintJson(json);
/// Converts JSON to a pretty printed string
String _prettyPrintJson(Map<String, dynamic> json) {
const encoder = JsonEncoder.withIndent(' ');
return encoder.convert(json);
}
/// Writes the arb file to the output directory
void writeTo(String outputDir, Map<String, dynamic> value) {
final file = File('$outputDir/$name')..createSync(recursive: true);
final content = _jsonToArb(value);
file.writeAsStringSync(content);
}
}
/// A l10n.yaml representation
class L10nYaml {
/// Creates a new l10n.yaml representation
L10nYaml({
required this.arbDir,
required this.outputDir,
required this.templateArbFile,
required this.outputLocalizationFile,
required this.outputClass,
required this.preferredSupportedLocales,
required this.path,
});
/// Creates a new l10n.yaml representation
L10nYaml.fromPath(this.path) {
_load();
}
/// Creates a new l10n.yaml representation from another
L10nYaml.from(
L10nYaml other, {
required this.path,
required this.outputClass,
}) : arbDir = other.arbDir,
outputDir = other.outputDir,
templateArbFile = other.templateArbFile,
outputLocalizationFile = other.outputLocalizationFile,
preferredSupportedLocales = other.preferredSupportedLocales;
/// The path to the l10n.yaml file
final String path;
late final String arbDir;
late final String outputDir;
late final String templateArbFile;
late final String outputLocalizationFile;
late final String outputClass;
late final String preferredSupportedLocales;
/// The arb directory
void _load() {
final l10nPath = '$path/l10n.yaml';
final file = File(l10nPath);
final content = file.readAsStringSync();
// print('$path/l10n.yaml:');
// print(content);
final map = _decodeSimpleYaml(content);
/*
arb-dir: lib/src/localization
template-arb-file: app_en.arb
output-localization-file: app_localizations.g.dart
output-dir: lib/src/localization
output-class: AppLocalizations
synthetic-package: false
untranslated-messages-file: missing-translations.txt
preferred-supported-locales: en
nullable-getter: true
*/
arbDir = map['arb-dir'] ?? '';
outputDir = map['output-dir'] ?? '';
templateArbFile = map['template-arb-file'] ?? '';
outputLocalizationFile = map['output-localization-file'] ?? '';
outputClass = map['output-class'] ?? '';
preferredSupportedLocales = map['preferred-supported-locales'] ?? '';
if (arbDir.isEmpty) {
throw Exception('arb-dir not found in $l10nPath');
}
if (outputDir.isEmpty) {
throw Exception('output-dir not found in $l10nPath');
}
if (outputClass.isEmpty) {
throw Exception('output-class not found in $l10nPath');
}
}
/// writes the yaml file
void write() {
final file = File('$path/l10n.yaml')..createSync(recursive: true);
final content = '''
# This file is auto-generated by the localization_extender.dart tool
arb-dir: $arbDir
output-dir: $outputDir
template-arb-file: $templateArbFile
output-localization-file: $outputLocalizationFile
output-class: $outputClass
preferred-supported-locales: $preferredSupportedLocales
synthetic-package: false
''';
file.writeAsStringSync(content);
}
// This function decodes YAML format String to a map
// without supporting nested entries
Map<String, dynamic> _decodeSimpleYaml(String yaml) {
final lines = yaml.split('\n');
final map = <String, dynamic>{};
for (final line in lines) {
final trimmedLine = line.trim();
if (trimmedLine.isEmpty || trimmedLine.startsWith('#')) {
continue;
}
final colonIndex = trimmedLine.indexOf(':');
final key = trimmedLine.substring(0, colonIndex);
final value = trimmedLine.substring(colonIndex + 1).trim();
map[key] = value;
}
return map;
}
}
extension _FileExtension on File {
String get name {
final parts = path.split(Platform.pathSeparator);
return parts.last;
}
}
| 0
|
mirrored_repositories/Inventory
|
mirrored_repositories/Inventory/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter4_listview/data/main_fetch_data.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.amber,
),
//home: new HomePage(),
home: new MainFetchData(),
);
}
}
| 0
|
mirrored_repositories/Inventory/lib
|
mirrored_repositories/Inventory/lib/data/main_fetch_data.dart
|
import 'dart:collection';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:flutter4_listview/model/UpdateRecord.dart';
import 'package:flutter4_listview/model/SimpleObject.dart';
import 'package:flutter4_listview/util/logger.dart';
class MainFetchData extends StatefulWidget {
@override
_MainFetchDataState createState() => _MainFetchDataState();
}
class _MainFetchDataState extends State<MainFetchData> {
static const channel =
const MethodChannel("exampleflutter.mfs.com.flutter3listview");
Future<Null> _openNewPage() async {
Catalog item = _allRecords[selectedIndex];
logMessage('_openNewPage with index ' + selectedIndex.toString());
_updateData(item);
final response =
await channel.invokeMethod("openPage", <String, dynamic>{
'item': item.item.value,
'cost': item.cost.value,
'stock': "1",
'category': item.category.value
});
print(response);
}
static final String getAllRecordsUrl =
"https://yourapp.kintone.com/k/v1/records.json?app=2&id=1";
static final String updateRecordUrl =
"https://yourapp.kintone.com/k/v1/record.json";
static final String sampleUrl = "https://jsonplaceholder.typicode.com/photos";
Map<String, String> requestHeaders = {
'X-Cybozu-API-token': 'yourtoken'
};
List<Catalog> _allRecords = List();
int selectedIndex = 0;
var isLoading = false;
// Fetch from Kintone Database
_fetchData() async {
setState(() {
isLoading = true;
});
final response = await http.get(getAllRecordsUrl, headers: requestHeaders);
if (response.statusCode == 200) {
logMessage('Fetched Data Now parsing');
final parsedJson = json.decode(response.body);
logMessage('Got Parsed Json ');
final recordsData = SimpleObject.fromJson(parsedJson);
_allRecords = (recordsData.records as List);
logMessage('Parsed Data and have list now');
setState(() {
isLoading = false;
});
} else {
throw Exception('Failed to load catalog2');
}
}
Map<String, String> updateRequestHeaders = {
'X-Cybozu-API-token': 'SrropGaww4HxLoicvqz7NWfrVcDFrO0nh91oV0di'
};
var stockMap = {
"app": 2,
"id": 1,
"record": {
"stock": {"value": "32"}
}
};
// Update Kintone Database
_updateData(Catalog item) async {
logMessage('_updateData record with index ' + selectedIndex.toString());
//String currentStockValue = _allRecords[selectedIndex].stock.value;
int currentStockValue = int.parse(_allRecords[selectedIndex].stock.value);
--currentStockValue;
var stockMap1 = new UpdateRecord(2,
int.parse(_allRecords[selectedIndex].Record_number.value),
new URecord(new UStock(currentStockValue.toString())));
String jsonString = jsonEncode(stockMap);
final response = await http.put(updateRecordUrl,
body: jsonString, headers: updateRequestHeaders);
if (response.statusCode == 200) {
logMessage('Succesfully updated record');
} else {
throw Exception('Failed to update record');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that
// was created by the App.build method, and use it to set
// our appbar title.
title: new Center(child: new Text("Catalog", textAlign: TextAlign.center)),
leading: new IconButton(
icon: new Icon(Icons.replay),
onPressed: _fetchData,
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add_shopping_cart),
onPressed: _openNewPage,
backgroundColor: Colors.red,
foregroundColor: Colors.black,
),
body: isLoading
? Center(
child: CircularProgressIndicator(),
)
: getHomePageBody(context));
}
// Build List of UI
getHomePageBody(BuildContext context) {
return ListView.builder(
itemCount: _allRecords.length,
itemBuilder: _getItemUI,
padding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
);
}
// Build UI Widget
Widget _getItemUI(BuildContext context, int index) {
return new Card(
child: new Column(
children: <Widget>[
new ListTile(
leading: new Image.network(
_allRecords[index].imgurl.value,
fit: BoxFit.contain,
height: 60.0,
width: 60.0,
),
title: new Text(
_allRecords[index].item.value,
style: new TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
),
subtitle: new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(_allRecords[index].category.value,
style: new TextStyle(
fontSize: 18.0, fontWeight: FontWeight.normal)),
new Text('Stock: ${_allRecords[index].stock.value}',
style: new TextStyle(
fontSize: 18.0, fontWeight: FontWeight.normal)),
]),
onTap: () {
selectedIndex = index;
_showSnackBar(context, _allRecords[index]);
},
)
],
));
}
_showSnackBar(BuildContext context, Catalog item) {
final SnackBar objSnackbar = new SnackBar(
content: new Text("1 ${item.item.value} ${item.category.value} is "
"selected"),
backgroundColor: Colors.amber,
);
Scaffold.of(context).showSnackBar(objSnackbar);
}
}
| 0
|
mirrored_repositories/Inventory/lib
|
mirrored_repositories/Inventory/lib/model/SimpleObject.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'SimpleObject.g.dart';
class SimpleObject {
const SimpleObject({
this.records,
});
@JsonKey(name: 'records')
final List<Catalog> records;
factory SimpleObject.fromJson(Map<String, dynamic> json) {
if (json == null) return null;
return SimpleObject(
records: json['records'] != null
? List<Catalog>.from(
json['records'].map((o) => Catalog.fromJson(o)))
: null);
}
}
@JsonSerializable()
class Catalog {
const Catalog({this.item, this.category,
this.imgurl, this.stock, this.cost,
this.Record_number});
final Item item;
final Category category;
final ImageUrl imgurl;
final Stock stock;
final Cost cost;
final RecordNumber Record_number;
factory Catalog.fromJson(Map<String, dynamic> json) =>
_$CatalogFromJson(json);
Map<String, dynamic> toJson() => _$CatalogToJson(this);
}
@JsonSerializable()
class Item {
final String type;
final String value;
Item(this.type, this.value);
factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json);
Map<String, dynamic> toJson() => _$ItemToJson(this);
}
@JsonSerializable()
class Category {
final String type;
final String value;
Category(this.type, this.value);
factory Category.fromJson(Map<String, dynamic> json) =>
_$CategoryFromJson(json);
Map<String, dynamic> toJson() => _$CategoryToJson(this);
}
@JsonSerializable()
class ImageUrl {
final String type;
final String value;
ImageUrl(this.type, this.value);
factory ImageUrl.fromJson(Map<String, dynamic> json) =>
_$ImageUrlFromJson(json);
Map<String, dynamic> toJson() => _$ImageUrlToJson(this);
}
@JsonSerializable()
class Stock {
final String type;
final String value;
Stock(this.type, this.value);
factory Stock.fromJson(Map<String, dynamic> json) => _$StockFromJson(json);
Map<String, dynamic> toJson() => _$StockToJson(this);
}
@JsonSerializable()
class Cost {
final String type;
final String value;
Cost(this.type, this.value);
factory Cost.fromJson(Map<String, dynamic> json) => _$CostFromJson(json);
Map<String, dynamic> toJson() => _$CostToJson(this);
}
@JsonSerializable()
class RecordNumber {
final String type;
final String value;
RecordNumber(this.type, this.value);
factory RecordNumber.fromJson(Map<String, dynamic> json) => _$RecordNumberFromJson(json);
Map<String, dynamic> toJson() => _$RecordNumberToJson(this);
}
| 0
|
mirrored_repositories/Inventory/lib
|
mirrored_repositories/Inventory/lib/model/UpdateRecord.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'UpdateRecord.g.dart';
class UpdateRecord {
final int app;
final int id;
final URecord record;
UpdateRecord(this.app, this.id, this.record);
UpdateRecord.fromJson(Map<String, dynamic> json)
: app = json['app'],
id = json['id'],
record = json['record'];
Map<String, dynamic> toJson() => {
'app': app,
'id': id,
'record': record,
};
}
@JsonSerializable()
class URecord {
final UStock stock;
URecord(this.stock);
URecord.fromJson(Map<String, dynamic> json) : stock = json['stock'];
Map<String, dynamic> toJson() => {
'stock': stock,
};
}
@JsonSerializable()
class UStock {
final String value;
UStock(this.value);
UStock.fromJson(Map<String, dynamic> json) : value = json['value'];
Map<String, dynamic> toJson() => {
'value': value,
};
}
| 0
|
mirrored_repositories/Inventory/lib
|
mirrored_repositories/Inventory/lib/model/SimpleObject.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'SimpleObject.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Catalog _$CatalogFromJson(Map<String, dynamic> json) {
return Catalog(
item: json['item'] == null
? null
: Item.fromJson(json['item'] as Map<String, dynamic>),
category: json['category'] == null
? null
: Category.fromJson(json['category'] as Map<String, dynamic>),
imgurl: json['imgurl'] == null
? null
: ImageUrl.fromJson(json['imgurl'] as Map<String, dynamic>),
stock: json['stock'] == null
? null
: Stock.fromJson(json['stock'] as Map<String, dynamic>),
cost: json['cost'] == null
? null
: Cost.fromJson(json['cost'] as Map<String, dynamic>),
Record_number: json['Record_number'] == null
? null
: RecordNumber.fromJson(
json['Record_number'] as Map<String, dynamic>));
}
Map<String, dynamic> _$CatalogToJson(Catalog instance) => <String, dynamic>{
'item': instance.item,
'category': instance.category,
'imgurl': instance.imgurl,
'stock': instance.stock,
'cost': instance.cost,
'Record_number': instance.Record_number
};
Item _$ItemFromJson(Map<String, dynamic> json) {
return Item(json['type'] as String, json['value'] as String);
}
Map<String, dynamic> _$ItemToJson(Item instance) =>
<String, dynamic>{'type': instance.type, 'value': instance.value};
Category _$CategoryFromJson(Map<String, dynamic> json) {
return Category(json['type'] as String, json['value'] as String);
}
Map<String, dynamic> _$CategoryToJson(Category instance) =>
<String, dynamic>{'type': instance.type, 'value': instance.value};
ImageUrl _$ImageUrlFromJson(Map<String, dynamic> json) {
return ImageUrl(json['type'] as String, json['value'] as String);
}
Map<String, dynamic> _$ImageUrlToJson(ImageUrl instance) =>
<String, dynamic>{'type': instance.type, 'value': instance.value};
Stock _$StockFromJson(Map<String, dynamic> json) {
return Stock(json['type'] as String, json['value'] as String);
}
Map<String, dynamic> _$StockToJson(Stock instance) =>
<String, dynamic>{'type': instance.type, 'value': instance.value};
Cost _$CostFromJson(Map<String, dynamic> json) {
return Cost(json['type'] as String, json['value'] as String);
}
Map<String, dynamic> _$CostToJson(Cost instance) =>
<String, dynamic>{'type': instance.type, 'value': instance.value};
RecordNumber _$RecordNumberFromJson(Map<String, dynamic> json) {
return RecordNumber(json['type'] as String, json['value'] as String);
}
Map<String, dynamic> _$RecordNumberToJson(RecordNumber instance) =>
<String, dynamic>{'type': instance.type, 'value': instance.value};
| 0
|
mirrored_repositories/Inventory/lib
|
mirrored_repositories/Inventory/lib/model/UpdateRecord.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'UpdateRecord.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
URecord _$URecordFromJson(Map<String, dynamic> json) {
return URecord(json['stock'] == null
? null
: UStock.fromJson(json['stock'] as Map<String, dynamic>));
}
Map<String, dynamic> _$URecordToJson(URecord instance) =>
<String, dynamic>{'stock': instance.stock};
UStock _$UStockFromJson(Map<String, dynamic> json) {
return UStock(json['value'] as String);
}
Map<String, dynamic> _$UStockToJson(UStock instance) =>
<String, dynamic>{'value': instance.value};
| 0
|
mirrored_repositories/Inventory/lib
|
mirrored_repositories/Inventory/lib/util/logger.dart
|
import 'package:logging/logging.dart';
final Logger log = new Logger('CATALOG')
..onRecord.listen((LogRecord rec) {
print('LOG ${rec.level.name}: ${rec.message}');
});
void logObject(String msg, Object o) {
log.info(msg);
for (String line in o.toString().split('\n')) {
log.info('-- $line');
}
}
void logMessage(String msg) {
log.info(msg);
}
void logException(String source, String message) {
log.warning('Exception ($source): $message');
}
| 0
|
mirrored_repositories/Inventory/lib
|
mirrored_repositories/Inventory/lib/generated/i18n.dart
|
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// ignore_for_file: non_constant_identifier_names
// ignore_for_file: camel_case_types
// ignore_for_file: prefer_single_quotes
//This file is automatically generated. DO NOT EDIT, all your changes would be lost.
class S implements WidgetsLocalizations {
const S();
static const GeneratedLocalizationsDelegate delegate =
GeneratedLocalizationsDelegate();
static S of(BuildContext context) => Localizations.of<S>(context, S);
@override
TextDirection get textDirection => TextDirection.ltr;
}
class $en extends S {
const $en();
}
class GeneratedLocalizationsDelegate extends LocalizationsDelegate<S> {
const GeneratedLocalizationsDelegate();
List<Locale> get supportedLocales {
return const <Locale>[
Locale("en", ""),
];
}
LocaleListResolutionCallback listResolution({Locale fallback}) {
return (List<Locale> locales, Iterable<Locale> supported) {
if (locales == null || locales.isEmpty) {
return fallback ?? supported.first;
} else {
return _resolve(locales.first, fallback, supported);
}
};
}
LocaleResolutionCallback resolution({Locale fallback}) {
return (Locale locale, Iterable<Locale> supported) {
return _resolve(locale, fallback, supported);
};
}
Locale _resolve(Locale locale, Locale fallback, Iterable<Locale> supported) {
if (locale == null || !isSupported(locale)) {
return fallback ?? supported.first;
}
final Locale languageLocale = Locale(locale.languageCode, "");
if (supported.contains(locale)) {
return locale;
} else if (supported.contains(languageLocale)) {
return languageLocale;
} else {
final Locale fallbackLocale = fallback ?? supported.first;
return fallbackLocale;
}
}
@override
Future<S> load(Locale locale) {
final String lang = getLang(locale);
if (lang != null) {
switch (lang) {
case "en":
return SynchronousFuture<S>(const $en());
default:
// NO-OP.
}
}
return SynchronousFuture<S>(const S());
}
@override
bool isSupported(Locale locale) =>
locale != null && supportedLocales.contains(locale);
@override
bool shouldReload(GeneratedLocalizationsDelegate old) => false;
}
String getLang(Locale l) => l == null
? null
: l.countryCode != null && l.countryCode.isEmpty
? l.languageCode
: l.toString();
| 0
|
mirrored_repositories/future_of_workout
|
mirrored_repositories/future_of_workout/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:future_of_workout/bootstrap.dart';
import 'package:local_storage_exercise_api/local_storage_exercise_api.dart';
import 'package:local_storage_goal_api/local_storage_goal_api.dart';
import 'package:local_storage_measurement_api/local_storage_measurement_api.dart';
import 'package:local_storage_user_api/local_storage_user_api.dart';
import 'package:local_storage_workout_api/local_storage_workout_api.dart';
import 'package:local_storage_workout_log_api/local_storage_workout_log_api.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
await Hive.initFlutter();
final exerciseApi = LocalStorageExerciseApi();
await exerciseApi.init();
final workoutApi = LocalStorageWorkoutApi();
await workoutApi.init();
final workoutLogApi = LocalStorageWorkoutLogApi();
await workoutLogApi.init();
final goalApi = LocalStorageGoalApi();
await goalApi.init();
final measurementApi = LocalStorageMeasurementApi();
await measurementApi.init();
final userApi = LocalStorageUserApi();
await userApi.init();
bootstrap(
workoutApi: workoutApi,
exerciseApi: exerciseApi,
workoutLogApi: workoutLogApi,
goalApi: goalApi,
measurementApi: measurementApi,
userApi: userApi,
);
}
| 0
|
mirrored_repositories/future_of_workout
|
mirrored_repositories/future_of_workout/lib/bootstrap.dart
|
import 'dart:async';
import 'dart:developer';
import 'package:exercise_api/exercise_api.dart';
import 'package:exercise_repository/exercise_repository.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:future_of_workout/src/app/app.dart';
import 'package:future_of_workout/src/app/app_bloc_observer.dart';
import 'package:future_of_workout/src/app/bloc/app_bloc.dart';
import 'package:future_of_workout/src/shared/logger.dart';
import 'package:goal_api/goal_api.dart';
import 'package:goal_repository/goal_repository.dart';
import 'package:measurement_repository/measurement_repository.dart';
import 'package:user_repository/user_repository.dart';
import 'package:workout_log_api/workout_log_api.dart';
import 'package:workout_log_repository/workout_log_repository.dart';
import 'package:workout_repository/workout_repository.dart';
void bootstrap({
required WorkoutApi workoutApi,
required ExerciseApi exerciseApi,
required WorkoutLogApi workoutLogApi,
required GoalApi goalApi,
required MeasurementApi measurementApi,
required UserApi userApi,
}) {
FlutterError.onError =
(details) => log(details.exceptionAsString(), stackTrace: details.stack);
Bloc.observer = AppBlocObserver();
final exerciseRepository = ExerciseRepository(exerciseApi: exerciseApi);
final workoutRepository = WorkoutRepository(workoutApi: workoutApi);
final workoutLogRepository =
WorkoutLogRepository(workoutLogApi: workoutLogApi);
final goalRepository = GoalRepository(goalApi: goalApi);
final measurementRepository =
MeasurementRepository(measurementApi: measurementApi);
final userRepository = UserRepository(userApi: userApi);
final appBloc = AppBloc(userRepository: userRepository)
..add(const AppLoading());
runZonedGuarded(
() => runApp(
FutureOfWorkoutApp(
exerciseRepository: exerciseRepository,
workoutRepository: workoutRepository,
workoutLogRepository: workoutLogRepository,
goalRepository: goalRepository,
measurementRepository: measurementRepository,
userRepository: userRepository,
appBloc: appBloc,
),
),
(error, stack) => logger.e(error.toString(), error, stack),
);
}
| 0
|
mirrored_repositories/future_of_workout/lib
|
mirrored_repositories/future_of_workout/lib/src/common.dart
|
export 'package:flutter/material.dart';
export 'package:flutter_bloc/flutter_bloc.dart';
export 'package:flutter_gen/gen_l10n/app_localizations.dart';
export 'shared/shared.dart';
export 'styles/styles.dart';
export 'widgets/widgets.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/setup/setup.dart
|
export 'bloc/setup_bloc.dart';
export 'view/setup_page.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup
|
mirrored_repositories/future_of_workout/lib/src/setup/view/view.dart
|
export 'pages/pages.dart';
export 'setup_page.dart';
export 'widgets/widgets.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup
|
mirrored_repositories/future_of_workout/lib/src/setup/view/setup_page.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:future_of_workout/src/setup/setup.dart';
import 'package:future_of_workout/src/setup/view/view.dart';
import 'package:future_of_workout/src/widgets/widgets.dart';
import 'package:measurement_repository/measurement_repository.dart';
import 'package:user_repository/user_repository.dart';
class SetupPage extends StatelessWidget {
const SetupPage({super.key});
static String name = '/setup';
static String path = name;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SetupBloc(
userRepository: context.read<UserRepository>(),
measurementRepository: context.read<MeasurementRepository>(),
),
child: const SetupPageView(),
);
}
}
class SetupPageView extends StatefulWidget {
const SetupPageView({super.key});
@override
State<SetupPageView> createState() => _SetupPageViewState();
}
class _SetupPageViewState extends State<SetupPageView> {
late PageController _pageController;
int _pageIndex = 0;
@override
void initState() {
_pageController = PageController(initialPage: _pageIndex);
super.initState();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
final _pages = const <Widget>[
GenderSetup(),
AgeSetup(),
HeightSetup(),
WeightSetup(),
FinishSetup(),
];
@override
Widget build(BuildContext context) {
return AppScaffold(
body: SafeArea(
child: Padding(
padding:
const EdgeInsets.only(top: 8, left: 16, right: 16, bottom: 32),
child: Column(
children: [
PositionIndicator(
length: _pages.length,
pageIndex: _pageIndex,
),
Expanded(
child: PageView(
physics: const NeverScrollableScrollPhysics(),
onPageChanged: (value) => setState(() {
_pageIndex = value;
}),
controller: _pageController,
children: _pages,
),
),
ButtonsRow(
length: _pages.length,
pageIndex: _pageIndex,
nextPage: () {
_pageController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.ease,
);
},
previousPage: () {
_pageController.previousPage(
duration: const Duration(milliseconds: 300),
curve: Curves.ease,
);
},
onFinish: () {
context.read<SetupBloc>().add(const SetupFinish());
},
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/widgets/buttons_row.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/setup/view/widgets/widgets.dart';
class ButtonsRow extends StatelessWidget {
const ButtonsRow({
required this.pageIndex,
required this.length,
required this.nextPage,
required this.previousPage,
required this.onFinish,
super.key,
});
final int pageIndex;
final int length;
final VoidCallback nextPage;
final VoidCallback previousPage;
final VoidCallback onFinish;
@override
Widget build(BuildContext context) {
final isLastPage = pageIndex == length - 1;
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ReturnButton(
isVisible: pageIndex != 0,
onPressed: previousPage,
),
ContinueButton(
onPressed: isLastPage ? onFinish : nextPage,
text: isLastPage
? context.locale.finishSetup
: context.locale.continueSetup,
),
],
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/widgets/widgets.dart
|
export 'buttons_row.dart';
export 'continue_button.dart';
export 'dot_indicator.dart';
export 'position_indicator.dart';
export 'return_button.dart';
export 'setup_content.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/widgets/setup_content.dart
|
import 'package:flutter/material.dart';
import 'package:future_of_workout/src/styles/app_text_style.dart';
class SetupContent extends StatelessWidget {
const SetupContent({
super.key,
required this.title,
required this.description,
required this.children,
});
final String title;
final String description;
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Column(
// mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: AppTextStyle.bold28),
const SizedBox(height: 8),
Text(description, style: AppTextStyle.regular16),
for (var item in children) ...[
const Spacer(),
item,
],
const Spacer(),
],
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/widgets/continue_button.dart
|
import 'package:future_of_workout/src/common.dart';
class ContinueButton extends StatelessWidget {
const ContinueButton({
required this.onPressed,
required this.text,
super.key,
});
final String text;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: ElevatedButton.icon(
label: Text(text),
icon: const AppIcon(iconData: AppIcons.right),
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
padding: const EdgeInsets.only(
top: 16,
bottom: 16,
left: 16,
right: 8,
),
),
onPressed: onPressed,
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/widgets/return_button.dart
|
import 'package:future_of_workout/src/common.dart';
class ReturnButton extends StatelessWidget {
const ReturnButton({
required this.onPressed,
this.isVisible = false,
super.key,
});
final bool isVisible;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return Visibility(
visible: isVisible,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
side: const BorderSide(
width: 4,
color: AppColors.yellow,
),
foregroundColor: AppColors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
padding: const EdgeInsets.all(16),
),
onPressed: onPressed,
child: const AppIcon(iconData: AppIcons.left),
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/widgets/position_indicator.dart
|
import 'package:flutter/material.dart';
import 'package:future_of_workout/src/setup/view/widgets/widgets.dart';
class PositionIndicator extends StatelessWidget {
const PositionIndicator({
required this.length,
required this.pageIndex,
super.key,
});
final int length;
final int pageIndex;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: SizedBox(
height: 32,
child: Row(
children: List.generate(
length,
(index) => DotIndicator(
isSelected: pageIndex == index,
isCompleted: pageIndex >= index,
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/widgets/dot_indicator.dart
|
import 'package:flutter/material.dart';
import 'package:future_of_workout/src/styles/styles.dart';
class DotIndicator extends StatelessWidget {
const DotIndicator({
super.key,
this.isSelected = false,
this.isCompleted = false,
});
final bool isSelected;
final bool isCompleted;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(right: 4),
child: AnimatedContainer(
curve: Curves.ease,
duration: const Duration(milliseconds: 300),
width: isSelected ? 64 : 16,
height: 16,
decoration: BoxDecoration(
color: isCompleted ? AppColors.yellow : AppColors.grey,
borderRadius: BorderRadius.circular(16),
),
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/pages/gender_setup.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/setup/setup.dart';
import 'package:future_of_workout/src/setup/view/widgets/widgets.dart';
import 'package:user_repository/user_repository.dart';
class GenderSetup extends StatelessWidget {
const GenderSetup({super.key});
@override
Widget build(BuildContext context) {
return SetupContent(
title: context.locale.setupGenderTitle,
description: context.locale.setupGenderDescription,
children: [
BlocBuilder<SetupBloc, SetupState>(
buildWhen: (previous, current) =>
previous.user.gender != current.user.gender,
builder: (context, state) {
return GridView(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
children: [
_GenderCard(
// TODO(Icon): Change icon
icon: Icons.male_rounded,
text: context.locale.setupGenderMale,
isSelected: state.user.gender == Gender.male,
onTap: () {
context
.read<SetupBloc>()
.add(const SetupGenderChange(gender: Gender.male));
},
),
_GenderCard(
// TODO(Icon): Change icon
icon: Icons.female_rounded,
text: context.locale.setupGenderFemale,
isSelected: state.user.gender == Gender.female,
onTap: () {
context
.read<SetupBloc>()
.add(const SetupGenderChange(gender: Gender.female));
},
),
_GenderCard(
// TODO(Icon): Change icon
icon: Icons.person,
text: context.locale.setupGenderOther,
isSelected: state.user.gender == Gender.other,
onTap: () {
context
.read<SetupBloc>()
.add(const SetupGenderChange(gender: Gender.other));
},
),
],
);
},
),
],
);
}
}
class _GenderCard extends StatelessWidget {
const _GenderCard({
required this.icon,
required this.text,
required this.onTap,
this.isSelected = false,
});
final IconData icon;
final String text;
final bool isSelected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return CustomCard(
padding: const EdgeInsets.all(8),
onTap: onTap,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// TODO(Icon): Change icon type
Icon(
icon,
size: 96,
color: isSelected ? AppColors.yellow : AppColors.grey,
),
Text(
text,
style: AppTextStyle.bold20,
textAlign: TextAlign.center,
),
],
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/pages/weight_setup.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/setup/setup.dart';
import 'package:future_of_workout/src/setup/view/widgets/widgets.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:user_repository/user_repository.dart';
class WeightSetup extends StatelessWidget {
const WeightSetup({super.key});
@override
Widget build(BuildContext context) {
return SetupContent(
title: context.locale.setupWeightTitle,
description: context.locale.setupWeightDescription,
children: [
const _WeightUnitBar(),
BlocBuilder<SetupBloc, SetupState>(
buildWhen: (previous, current) =>
previous.user.weightUnit != current.user.weightUnit,
builder: (context, state) {
switch (state.user.weightUnit) {
case WeightUnit.kilogram:
return _WeightKilogramPicker(weight: state.user.weight);
case WeightUnit.pounds:
return _WeightPoundsPicker(weight: state.user.weight);
}
},
),
],
);
}
}
class _WeightUnitBar extends StatelessWidget {
const _WeightUnitBar();
@override
Widget build(BuildContext context) {
return BlocBuilder<SetupBloc, SetupState>(
buildWhen: (previous, current) =>
previous.user.weightUnit != current.user.weightUnit,
builder: (context, state) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: ToggleBar(
initialIndex: state.user.weightUnit == WeightUnit.kilogram ? 0 : 1,
onChange: (value) {
final unit = WeightUnit.values[value];
if (unit != state.user.weightUnit) {
context.read<SetupBloc>().add(
SetupWeightUnitChange(
weightUnit: unit,
),
);
}
},
tabs: [
Tab(
child: Text(
context.locale.weightUnitType(WeightUnit.kilogram.name),
),
),
Tab(
child: Text(
context.locale.weightUnitType(WeightUnit.pounds.name),
),
),
],
),
);
},
);
}
}
class _WeightKilogramPicker extends StatefulWidget {
const _WeightKilogramPicker({required this.weight});
final double weight;
@override
State<_WeightKilogramPicker> createState() => __WeightKilogramPickerState();
}
class __WeightKilogramPickerState extends State<_WeightKilogramPicker> {
late double _value;
final minValue = 25;
final maxValue = 255;
@override
void initState() {
_value = widget.weight.clamp(minValue, maxValue).toDouble();
super.initState();
}
@override
Widget build(BuildContext context) {
const itemHeight = 64.0;
const itemWidth = 128.0;
return Center(
child: DecimalNumberPicker(
decimalDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
integerDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
itemHeight: itemHeight,
itemWidth: itemWidth,
itemCount: 7,
textStyle: AppTextStyle.semiBold20,
selectedTextStyle:
AppTextStyle.bold48.copyWith(color: AppColors.yellow),
minValue: minValue,
maxValue: maxValue,
value: _value,
onChanged: (value) => setState(() {
_value = value;
context.read<SetupBloc>().add(SetupWeightChange(weight: value));
}),
),
);
}
}
class _WeightPoundsPicker extends StatefulWidget {
const _WeightPoundsPicker({required this.weight});
final double weight;
@override
State<_WeightPoundsPicker> createState() => __WeightPoundsPickerState();
}
class __WeightPoundsPickerState extends State<_WeightPoundsPicker> {
late double _value;
final minValue = 55;
final maxValue = 562;
@override
void initState() {
_value = double.parse(
widget.weight.clamp(minValue, maxValue).toStringAsFixed(1),
);
super.initState();
}
@override
Widget build(BuildContext context) {
const itemHeight = 64.0;
const itemWidth = 128.0;
return Center(
child: DecimalNumberPicker(
decimalDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
integerDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
itemHeight: itemHeight,
itemWidth: itemWidth,
itemCount: 7,
textStyle: AppTextStyle.semiBold20,
selectedTextStyle:
AppTextStyle.bold48.copyWith(color: AppColors.yellow),
minValue: minValue,
maxValue: maxValue,
value: _value,
onChanged: (value) => setState(() {
_value = value;
context.read<SetupBloc>().add(SetupWeightChange(weight: value));
}),
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/pages/pages.dart
|
export 'age_setup.dart';
export 'finish_setup.dart';
export 'gender_setup.dart';
export 'height_setup.dart';
export 'weight_setup.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/pages/finish_setup.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/setup/setup.dart';
import 'package:future_of_workout/src/setup/view/widgets/widgets.dart';
class FinishSetup extends StatelessWidget {
const FinishSetup({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<SetupBloc, SetupState>(
buildWhen: (previous, current) => previous.user != current.user,
builder: (context, state) {
final user = state.user;
return SetupContent(
title: context.locale.finishSetup,
description: '',
children: [
GridView(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
children: [
// TODO(Function): onTap go to specific page
_DataCard(
text: context.locale.gender,
value: context.locale.genderType(user.gender.name),
),
_DataCard(
text: context.locale.age,
value: user.age.toString(),
),
_DataCard(
text: context.locale.height,
value: user.height.toString(),
suffix: user.lengthUnit.sufix,
),
_DataCard(
text: context.locale.settingsWeight,
value: user.weight.toString(),
suffix: user.weightUnit.sufix,
),
],
),
],
);
},
);
}
}
class _DataCard extends StatelessWidget {
const _DataCard({
required this.text,
required this.value,
this.suffix = '',
this.onTap,
});
final String text;
final String value;
final String suffix;
final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
return CustomCard(
onTap: onTap,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(text, style: AppTextStyle.semiBold24),
BoldText(boldText: value, mediumText: suffix),
],
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/pages/height_setup.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/setup/setup.dart';
import 'package:future_of_workout/src/setup/view/widgets/widgets.dart';
import 'package:numberpicker/numberpicker.dart';
import 'package:user_repository/user_repository.dart';
class HeightSetup extends StatelessWidget {
const HeightSetup({super.key});
@override
Widget build(BuildContext context) {
return SetupContent(
title: context.locale.setupHeightTitle,
description: context.locale.setupHeightDescription,
children: [
const _LengthUnitBar(),
BlocBuilder<SetupBloc, SetupState>(
buildWhen: (previous, current) =>
previous.user.lengthUnit != current.user.lengthUnit,
builder: (context, state) {
switch (state.user.lengthUnit) {
case LengthUnit.centimeter:
return _HeightCentimeterPicker(height: state.user.height);
case LengthUnit.inch:
return _HeightInchPicker(height: state.user.height);
}
},
),
],
);
}
}
class _LengthUnitBar extends StatelessWidget {
const _LengthUnitBar();
@override
Widget build(BuildContext context) {
return BlocBuilder<SetupBloc, SetupState>(
buildWhen: (previous, current) =>
previous.user.lengthUnit != current.user.lengthUnit,
builder: (context, state) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: ToggleBar(
initialIndex:
state.user.lengthUnit == LengthUnit.centimeter ? 0 : 1,
onChange: (value) {
final unit = LengthUnit.values[value];
if (unit != state.user.lengthUnit) {
context.read<SetupBloc>().add(
SetupLengthUnitChange(
lengthUnit: unit,
),
);
}
},
tabs: [
Tab(
child: Text(
context.locale.lengthUnitType(LengthUnit.centimeter.name),
),
),
Tab(
child: Text(
context.locale.lengthUnitType(LengthUnit.inch.name),
),
),
],
),
);
},
);
}
}
class _HeightCentimeterPicker extends StatefulWidget {
const _HeightCentimeterPicker({required this.height});
final double height;
@override
State<_HeightCentimeterPicker> createState() =>
_HeightCentimeterPickerState();
}
class _HeightCentimeterPickerState extends State<_HeightCentimeterPicker> {
late double _value;
final minValue = 100;
final maxValue = 255;
@override
void initState() {
_value = widget.height;
super.initState();
}
@override
Widget build(BuildContext context) {
const itemHeight = 64.0;
const itemWidth = 128.0;
return Center(
child: DecimalNumberPicker(
decimalDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
integerDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
itemHeight: itemHeight,
itemWidth: itemWidth,
itemCount: 7,
textStyle: AppTextStyle.semiBold20,
selectedTextStyle:
AppTextStyle.bold48.copyWith(color: AppColors.yellow),
minValue: minValue,
maxValue: maxValue,
value: _value,
onChanged: (value) => setState(() {
_value = value;
context.read<SetupBloc>().add(SetupHeightChange(height: value));
}),
),
);
}
}
class _HeightInchPicker extends StatefulWidget {
const _HeightInchPicker({required this.height});
final double height;
@override
State<_HeightInchPicker> createState() => _HeightInchPickerState();
}
class _HeightInchPickerState extends State<_HeightInchPicker> {
late double _value;
final minValue = 40;
final maxValue = 100;
@override
void initState() {
_value = widget.height;
super.initState();
}
@override
Widget build(BuildContext context) {
const itemHeight = 64.0;
const itemWidth = 128.0;
return Center(
child: DecimalNumberPicker(
decimalDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
integerDecoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
itemHeight: itemHeight,
itemWidth: itemWidth,
itemCount: 7,
textStyle: AppTextStyle.semiBold20,
selectedTextStyle:
AppTextStyle.bold48.copyWith(color: AppColors.yellow),
minValue: minValue,
maxValue: maxValue,
value: _value,
onChanged: (value) => setState(() {
_value = value;
context.read<SetupBloc>().add(SetupHeightChange(height: value));
}),
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup/view
|
mirrored_repositories/future_of_workout/lib/src/setup/view/pages/age_setup.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/setup/setup.dart';
import 'package:future_of_workout/src/setup/view/widgets/widgets.dart';
import 'package:numberpicker/numberpicker.dart';
class AgeSetup extends StatefulWidget {
const AgeSetup({super.key});
@override
State<AgeSetup> createState() => _AgeSetupState();
}
class _AgeSetupState extends State<AgeSetup> {
int? _value;
@override
Widget build(BuildContext context) {
_value ??= context.read<SetupBloc>().state.user.age;
const itemHeight = 64.0;
const itemWidth = 128.0;
return SetupContent(
title: context.locale.setupAgeTitle,
description: context.locale.setupAgeDescription,
children: [
Center(
child: NumberPicker(
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: AppColors.yellow, width: 2),
bottom: BorderSide(color: AppColors.yellow, width: 2),
),
),
itemHeight: itemHeight,
itemWidth: itemWidth,
itemCount: 7,
textStyle: AppTextStyle.semiBold20,
selectedTextStyle:
AppTextStyle.bold48.copyWith(color: AppColors.yellow),
minValue: 1,
maxValue: 123,
value: _value!,
onChanged: (value) => setState(() {
_value = value;
context.read<SetupBloc>().add(SetupAgeChange(age: value));
}),
),
),
],
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup
|
mirrored_repositories/future_of_workout/lib/src/setup/bloc/setup_state.dart
|
part of 'setup_bloc.dart';
enum SetupStatus {
initial,
updating,
finish,
failure,
}
class SetupState extends Equatable {
const SetupState({
this.status = SetupStatus.initial,
this.user = const User(),
});
final SetupStatus status;
final User user;
@override
List<Object> get props => [status, user];
SetupState copyWith({
SetupStatus? status,
User? user,
}) {
return SetupState(
status: status ?? this.status,
user: user ?? this.user,
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup
|
mirrored_repositories/future_of_workout/lib/src/setup/bloc/setup_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:future_of_workout/src/shared/shared.dart';
import 'package:measurement_repository/measurement_repository.dart';
import 'package:user_repository/user_repository.dart';
part 'setup_event.dart';
part 'setup_state.dart';
class SetupBloc extends Bloc<SetupEvent, SetupState> {
SetupBloc({
required UserRepository userRepository,
required MeasurementRepository measurementRepository,
}) : _userRepository = userRepository,
_measurementRepository = measurementRepository,
super(const SetupState()) {
on<SetupGenderChange>(_onGenderChange);
on<SetupAgeChange>(_onAgeChange);
on<SetupHeightChange>(_onHeightChange);
on<SetupLengthUnitChange>(_onLengthUnitChange);
on<SetupWeightChange>(_onWeightChange);
on<SetupWeightUnitChange>(_onWeightUnitChange);
on<SetupFinish>(_onFinish);
}
final UserRepository _userRepository;
final MeasurementRepository _measurementRepository;
void _onGenderChange(
SetupGenderChange event,
Emitter<SetupState> emit,
) {
final user = state.user.copyWith(gender: event.gender);
emit(state.copyWith(user: user));
}
void _onAgeChange(
SetupAgeChange event,
Emitter<SetupState> emit,
) {
final user = state.user.copyWith(age: event.age);
emit(state.copyWith(user: user));
}
void _onHeightChange(
SetupHeightChange event,
Emitter<SetupState> emit,
) {
final user = state.user.copyWith(height: event.height);
emit(state.copyWith(user: user));
}
void _onLengthUnitChange(
SetupLengthUnitChange event,
Emitter<SetupState> emit,
) {
final double height;
switch (event.lengthUnit) {
case LengthUnit.centimeter:
height = UnitConverter.inchesToCentimeters(length: state.user.height)
.toPrecision(1);
break;
case LengthUnit.inch:
height = UnitConverter.centimetersToInches(length: state.user.height)
.toPrecision(1);
break;
}
final user = state.user.copyWith(
lengthUnit: event.lengthUnit,
height: height,
);
emit(state.copyWith(user: user));
}
void _onWeightChange(
SetupWeightChange event,
Emitter<SetupState> emit,
) {
final user = state.user.copyWith(weight: event.weight);
emit(state.copyWith(user: user));
}
void _onWeightUnitChange(
SetupWeightUnitChange event,
Emitter<SetupState> emit,
) {
final double weight;
switch (event.weightUnit) {
case WeightUnit.kilogram:
weight = UnitConverter.poundsToKilograms(weight: state.user.weight)
.toPrecision(1);
break;
case WeightUnit.pounds:
weight = UnitConverter.kilogramsToPounds(weight: state.user.weight)
.toPrecision(1);
break;
}
final user = state.user.copyWith(
weightUnit: event.weightUnit,
weight: weight,
);
emit(state.copyWith(user: user));
}
Future<void> _onFinish(
SetupFinish event,
Emitter<SetupState> emit,
) async {
emit(state.copyWith(status: SetupStatus.updating));
var user = state.user;
if (user.lengthUnit == LengthUnit.inch) {
final height =
UnitConverter.inchesToCentimeters(length: state.user.height)
.toPrecision(1);
user = user.copyWith(height: height);
}
if (user.weightUnit == WeightUnit.pounds) {
final weight = UnitConverter.poundsToKilograms(weight: state.user.weight)
.toPrecision(1);
user = user.copyWith(weight: weight);
}
Measurement measurement;
try {
measurement = _measurementRepository.get(dateTime: DateTime.now());
} on MeasurementNotFoundException catch (_) {
measurement = Measurement(date: DateTime.now().toDay());
}
await _userRepository.saveUser(user);
await _measurementRepository
.saveMeasurement(measurement.copyWith(weight: () => user.weight));
emit(state.copyWith(status: SetupStatus.finish));
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/setup
|
mirrored_repositories/future_of_workout/lib/src/setup/bloc/setup_event.dart
|
part of 'setup_bloc.dart';
abstract class SetupEvent extends Equatable {
const SetupEvent();
@override
List<Object> get props => [];
}
class SetupGenderChange extends SetupEvent {
const SetupGenderChange({required this.gender});
final Gender gender;
@override
List<Object> get props => [gender];
}
class SetupAgeChange extends SetupEvent {
const SetupAgeChange({required this.age});
final int age;
@override
List<Object> get props => [age];
}
class SetupHeightChange extends SetupEvent {
const SetupHeightChange({required this.height});
final double height;
@override
List<Object> get props => [height];
}
class SetupLengthUnitChange extends SetupEvent {
const SetupLengthUnitChange({required this.lengthUnit});
final LengthUnit lengthUnit;
@override
List<Object> get props => [lengthUnit];
}
class SetupWeightChange extends SetupEvent {
const SetupWeightChange({required this.weight});
final double weight;
@override
List<Object> get props => [weight];
}
class SetupWeightUnitChange extends SetupEvent {
const SetupWeightUnitChange({required this.weightUnit});
final WeightUnit weightUnit;
@override
List<Object> get props => [weightUnit];
}
class SetupFinish extends SetupEvent {
const SetupFinish();
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/logger.dart
|
import 'package:logger/logger.dart';
Logger logger = Logger(
printer: PrettyPrinter(),
);
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/ticker.dart
|
import 'dart:async';
class Ticker {
const Ticker();
Stream<int> tick({required int time}) {
const duration = Duration(seconds: 1);
return Stream.periodic(duration, (x) => x + time);
}
Stream<int> countdown({required int time}) {
const duration = Duration(seconds: 1);
return Stream.periodic(duration, (x) => time - x - 1).take(time);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/period.dart
|
enum Period {
week(days: 7),
oneMounth(days: 30),
threeMounth(days: 90),
sixMounth(days: 180),
year(days: 365);
const Period({required this.days});
final int days;
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/unit_converter.dart
|
import 'package:future_of_workout/src/shared/shared.dart';
import 'package:user_repository/user_repository.dart';
class UnitConverter {
const UnitConverter._();
static const double _kilogramsToPoundsConversionValue = 2.204622622;
static const double _centimetersToInchesConversionValue = 0.393700787402;
static double kilogramsToPounds({required double weight}) {
return weight * _kilogramsToPoundsConversionValue;
}
static double poundsToKilograms({required double weight}) {
return weight * (1 / _kilogramsToPoundsConversionValue);
}
static double centimetersToInches({required double length}) {
return length * _centimetersToInchesConversionValue;
}
static double inchesToCentimeters({required double length}) {
return length * (1 / _centimetersToInchesConversionValue);
}
static double dispalyedWeight({
required WeightUnit unit,
required double value,
}) {
switch (unit) {
case WeightUnit.kilogram:
return value.toPrecision(1);
case WeightUnit.pounds:
return kilogramsToPounds(weight: value).toPrecision(1);
}
}
static double dataWeight({
required WeightUnit unit,
required double value,
}) {
switch (unit) {
case WeightUnit.kilogram:
return value;
case WeightUnit.pounds:
return poundsToKilograms(weight: value);
}
}
static double dispalyedLength({
required LengthUnit unit,
required double value,
}) {
switch (unit) {
case LengthUnit.centimeter:
return value.toPrecision(1);
case LengthUnit.inch:
return centimetersToInches(length: value).toPrecision(2);
}
}
static double dataLength({
required LengthUnit unit,
required double value,
}) {
switch (unit) {
case LengthUnit.centimeter:
return value;
case LengthUnit.inch:
return inchesToCentimeters(length: value);
}
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/shared.dart
|
export 'calories_calculator.dart';
export 'extensions.dart';
export 'formatter.dart';
export 'logger.dart';
export 'one_rep_max_calculator.dart';
export 'period.dart';
export 'ticker.dart';
export 'unit_converter.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/calories_calculator.dart
|
import 'package:workout_log_repository/workout_log_repository.dart';
class CaloriesCalculator {
const CaloriesCalculator._();
static int inWorkout({
required double userWeight,
required WorkoutLog workout,
}) {
final finished = <ExerciseSeriesLog>[];
for (final exercise in workout.workoutExerciseLogs) {
final series =
exercise.exerciseSeriesLogs.where((series) => series.isFinished);
finished.addAll(series);
}
if (finished.isEmpty) {
return 0;
}
final intensity = finished
.map((series) => series.intensity.value)
.reduce((value, element) => value + element) /
finished.length;
final met = intensity * 10;
final time = finished
.map((series) => series.rest)
.reduce((value, element) => value + element) /
60;
final calories = (time * met * userWeight) / 200;
return calories.round();
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/formatter.dart
|
import 'package:flutter/services.dart';
class NumericalRangeFormatter extends TextInputFormatter {
NumericalRangeFormatter({required this.min, required this.max});
final int min;
final int max;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
if (newValue.text == '') {
return newValue;
} else if ((int.tryParse(newValue.text) ?? double.parse(newValue.text)) <
min) {
return TextEditingValue(text: min.toString());
} else {
return (int.tryParse(newValue.text) ?? double.parse(newValue.text)) > max
? oldValue
: newValue;
}
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/one_rep_max_calculator.dart
|
import 'package:workout_log_repository/workout_log_repository.dart';
class OneRepMaxCalculator {
const OneRepMaxCalculator._();
static double calculate({
required int reps,
required double weight,
required SeriesLogIntensity intensity,
}) {
final maxReps = _getMaxReps(intensity: intensity, reps: reps);
final percentage = _getPercentage(maxReps: maxReps);
return weight * 1 / percentage;
}
static double _getPercentage({required int maxReps}) {
switch (maxReps) {
case 2:
return 0.97;
case 3:
return 0.94;
case 4:
return 0.92;
case 5:
return 0.89;
case 6:
return 0.86;
case 7:
return 0.83;
case 8:
return 0.81;
case 9:
return 0.78;
case 10:
return 0.75;
case 11:
return 0.73;
case 12:
return 0.71;
case 13:
return 0.70;
case 14:
return 0.68;
case 15:
return 0.67;
case 16:
return 0.65;
case 17:
return 0.64;
case 18:
return 0.63;
case 19:
return 0.61;
case 20:
return 0.60;
case 21:
return 0.59;
case 22:
return 0.58;
case 23:
return 0.57;
case 24:
return 0.56;
case 25:
return 0.55;
case 26:
return 0.54;
case 27:
return 0.53;
case 28:
return 0.52;
case 29:
return 0.51;
case 30:
return 0.5;
}
return 1;
}
static int _getMaxReps({
required int reps,
required SeriesLogIntensity intensity,
}) {
switch (intensity) {
case SeriesLogIntensity.veryLight:
return reps + 6;
case SeriesLogIntensity.light:
return reps + 4;
case SeriesLogIntensity.moderate:
return reps + 2;
case SeriesLogIntensity.vigorous:
return reps + 1;
case SeriesLogIntensity.maximum:
return reps;
case SeriesLogIntensity.tooMuch:
return reps - 1;
}
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/shared/extensions.dart
|
import 'package:future_of_workout/src/common.dart';
extension DarkenAndLighten on Color {
Color darken({double amount = 0.1}) {
assert(amount >= 0 && amount <= 1, 'Amount should be between 0 and 1');
final hsl = HSLColor.fromColor(this);
final hslDark = hsl.withLightness((hsl.lightness - amount).clamp(0.0, 1.0));
return hslDark.toColor();
}
Color lighten({double amount = 0.1}) {
assert(amount >= 0 && amount <= 1, 'Amount should be between 0 and 1');
final hsl = HSLColor.fromColor(this);
final hslLight =
hsl.withLightness((hsl.lightness + amount).clamp(0.0, 1.0));
return hslLight.toColor();
}
}
extension DateTimeExtension on DateTime {
DateTime toDay() {
return DateTime(year, month, day);
}
bool isTheSameDay(DateTime date) {
return difference(date).inDays == 0;
}
bool isToday() {
return isTheSameDay(DateTime.now());
}
}
extension DoubleExtension on double {
double toPrecision(int precision) {
return double.parse(toStringAsFixed(precision));
}
}
extension BuildContextExtension on BuildContext {
AppLocalizations get locale => AppLocalizations.of(this)!;
String? get languageCode => Localizations.localeOf(this).languageCode;
}
extension StringExtension on String {
String withDefault([String defaultValue = '']) {
final temp = isEmpty ? defaultValue : this;
return temp;
}
String capitalize() {
return '${this[0].toUpperCase()}${substring(1).toLowerCase()}';
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout.dart
|
export 'current_workout/current_workout.dart';
export 'current_workout_exercise/current_workout_exercise.dart';
export 'current_workout_rest/current_workout_rest.dart';
export 'current_workout_summary/current_wokrout_summary.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout_rest/current_workout_rest.dart
|
export 'view/view.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout_rest
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout_rest/view/view.dart
|
export 'current_workout_rest_page.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout_rest
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout_rest/view/current_workout_rest_page.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
import 'package:future_of_workout/src/styles/styles.dart';
import 'package:future_of_workout/src/widgets/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:lottie/lottie.dart';
class CurrentWorkoutRestPage extends StatelessWidget {
const CurrentWorkoutRestPage({super.key});
static String name = 'rest';
static String path = name;
static Map<String, String> params({required String workoutExerciseId}) => {
'homePageTab': CurrentWorkoutPage.name,
'currentWorkoutExerciseId': workoutExerciseId,
};
@override
Widget build(BuildContext context) {
return BlocListener<CurrentWorkoutBloc, CurrentWorkoutState>(
listenWhen: (previous, current) => previous.status != current.status,
listener: (context, state) {
if (state.status == CurrentWorkoutStatus.rest) {
ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
}
if (state.status == CurrentWorkoutStatus.restComplete) {
context.pop();
}
},
child: AppScaffold(
title: 'Rest',
body: Stack(
children: [
Center(
child: Column(
children: [
Lottie.asset('assets/lottie/timer.json'),
const _TimerText(),
],
),
),
const Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: EdgeInsets.all(16),
child: _TimerActions(),
),
)
],
),
),
);
}
}
class _TimerActions extends StatelessWidget {
const _TimerActions();
@override
Widget build(BuildContext context) {
return BlocBuilder<CurrentWorkoutBloc, CurrentWorkoutState>(
buildWhen: (previous, current) => previous.status != current.status,
builder: (context, state) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_subtractButton(context),
_stopButton(context),
_addButton(context),
],
);
},
);
}
Widget _stopButton(BuildContext context) {
return CircleButton(
size: 64,
onTap: () => context
.read<CurrentWorkoutBloc>()
.add(const CurrentWorkoutRestStop()),
child: const Icon(Icons.stop),
);
}
Widget _addButton(BuildContext context) {
const value = 15;
return CircleButton(
onTap: () => context
.read<CurrentWorkoutBloc>()
.add(const CurrentWorkoutRestAdd(value: value)),
child: Text(
'+$value',
style: AppTextStyle.semiBold20,
),
);
}
Widget _subtractButton(BuildContext context) {
const value = 15;
return CircleButton(
onTap: () => context
.read<CurrentWorkoutBloc>()
.add(const CurrentWorkoutRestSubtract(value: value)),
child: Text(
'-$value',
style: AppTextStyle.semiBold20,
),
);
}
}
class _TimerText extends StatelessWidget {
const _TimerText();
@override
Widget build(BuildContext context) {
return BlocBuilder<CurrentWorkoutBloc, CurrentWorkoutState>(
buildWhen: (previous, current) =>
previous.restDuration != current.restDuration &&
current.restDuration != null,
builder: (context, state) {
final duration = state.restDuration!;
final minutesStr =
((duration / 60) % 60).floor().toString().padLeft(2, '0');
final secondStr = (duration % 60).toString().padLeft(2, '0');
return Text(
'$minutesStr:$secondStr',
style: AppTextStyle.bold96,
);
},
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/current_workout.dart
|
export 'bloc/current_workout_bloc.dart';
export 'view/view.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/view.dart
|
export 'current_workout_page.dart';
export 'widgets/widgets.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/current_workout_page.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
import 'package:future_of_workout/src/home/home.dart';
import 'package:future_of_workout/src/widgets/widgets.dart';
import 'package:go_router/go_router.dart';
class CurrentWorkoutPage extends StatelessWidget {
const CurrentWorkoutPage({super.key});
static String name = 'currentWorkout';
@override
Widget build(BuildContext context) {
return HomeWrapper(
body: BlocConsumer<CurrentWorkoutBloc, CurrentWorkoutState>(
listenWhen: (previous, current) => previous != current,
listener: (context, state) {
if (state.workoutLog == null) {
context
.read<NavigationCubit>()
.changeDestination(item: HomeNavigationItem.workouts);
}
if (state.status == CurrentWorkoutStatus.finish) {
ScaffoldMessenger.maybeOf(context)?.hideCurrentMaterialBanner();
context.goNamed(
CurrentWorkoutSummaryPage.name,
params: {
'homePageTab': CurrentWorkoutPage.name,
},
);
}
},
buildWhen: (previous, current) =>
previous.status != current.status ||
previous.workoutLog != current.workoutLog,
builder: (context, state) {
if (state.workoutLog != null) {
return ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
physics: const BouncingScrollPhysics(),
children: const [
//TitleCard(),
FinishButton(),
CurrentWorkoutContent(),
],
// ),
);
}
if (state.status == CurrentWorkoutStatus.failure) {
return const AppError();
}
return const AppLoading();
},
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/widgets/title_card.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
import 'package:future_of_workout/src/styles/app_text_style.dart';
import 'package:future_of_workout/src/widgets/cards/cards.dart';
class TitleCard extends StatelessWidget {
const TitleCard({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<CurrentWorkoutBloc, CurrentWorkoutState>(
builder: (context, state) {
final workout = state.workoutLog!;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: CustomCard(
padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
flex: 3,
child: Text(
workout.name,
style: AppTextStyle.semiBold24,
),
),
const Flexible(
child: WorkoutTime(),
)
],
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/widgets/workout_time.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
import 'package:future_of_workout/src/styles/styles.dart';
class WorkoutTime extends StatelessWidget {
const WorkoutTime({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<CurrentWorkoutBloc, CurrentWorkoutState>(
buildWhen: (previous, current) => previous.time != current.time,
builder: (context, state) {
final time = Duration(seconds: state.time);
String twoDigits(int n) => n.toString().padLeft(2, '0');
final hours = twoDigits(time.inHours.remainder(24));
final minutes = twoDigits(time.inMinutes.remainder(60));
final seconds = twoDigits(time.inSeconds.remainder(60));
return Text(
'$hours:$minutes:$seconds',
style: AppTextStyle.semiBold20,
);
},
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/widgets/exercise_logs_list.dart
|
import 'dart:ui';
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
import 'package:go_router/go_router.dart';
class ExerciseLogsList extends StatelessWidget {
const ExerciseLogsList({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<CurrentWorkoutBloc, CurrentWorkoutState>(
buildWhen: (previous, current) =>
previous.workoutLog?.workoutExerciseLogs !=
current.workoutLog?.workoutExerciseLogs,
builder: (context, state) {
final list = state.workoutLog!.workoutExerciseLogs;
return ReorderableListView.builder(
physics: const NeverScrollableScrollPhysics(),
itemCount: list.length,
shrinkWrap: true,
proxyDecorator: _proxyDecorator,
onReorder: (oldIndex, newIndex) {
context.read<CurrentWorkoutBloc>().add(
CurrentWorkoutReorder(
oldIndex: oldIndex,
newIndex: newIndex,
),
);
},
itemBuilder: (context, index) {
final item = list[index];
return WorkoutExerciseLogItem(
key: Key('workout_exercise_log_item_${item.id}'),
workoutExerciseLog: item,
onTap: () {
if (state.workoutExerciseId == item.id) {
ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
}
context.goNamed(
CurrentWorkoutExercisePage.name,
params: CurrentWorkoutExercisePage.params(
workoutExerciseLog: item.id,
),
);
},
);
},
);
},
);
}
Widget _proxyDecorator(Widget child, int index, Animation<double> animation) {
return AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget? child) {
final animValue = Curves.easeInOut.transform(animation.value);
final elevation = lerpDouble(0, 6, animValue)!;
return Material(
elevation: elevation,
color: Colors.transparent,
shadowColor: Colors.transparent,
child: child,
);
},
child: child,
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/widgets/add_exercise.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
import 'package:future_of_workout/src/exercise/exercise.dart';
import 'package:go_router/go_router.dart';
class AddExercise extends StatelessWidget {
const AddExercise({super.key});
@override
Widget build(BuildContext context) {
return ListAddButton(
text: context.locale.addExercise,
onTap: () {
context.pushNamed(
ExerciseListPage.name,
extra: ExerciseListExtra(
selectionType: SelectionType.multiple,
onConfirm: (selected) async {
context
.read<CurrentWorkoutBloc>()
.add(CurrentWorkoutAdd(exercises: selected));
},
),
);
},
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/widgets/widgets.dart
|
export 'add_exercise.dart';
export 'current_workout_content.dart';
export 'exercise_logs_list.dart';
export 'finish_button.dart';
export 'title_card.dart';
export 'workout_time.dart';
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/widgets/current_workout_content.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
class CurrentWorkoutContent extends StatelessWidget {
const CurrentWorkoutContent({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<CurrentWorkoutBloc, CurrentWorkoutState>(
buildWhen: (previous, current) =>
previous.workoutLog?.workoutExerciseLogs !=
current.workoutLog?.workoutExerciseLogs,
builder: (context, state) {
final isEmpty = state.workoutLog!.workoutExerciseLogs.isEmpty;
return Column(
children: [
Visibility(
visible: !isEmpty,
child: const ExerciseLogsList(),
),
const AddExercise(),
Visibility(
visible: isEmpty,
child: AppEmptyList(
text: context.locale.addExerciseText,
),
),
],
);
},
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/view/widgets/finish_button.dart
|
import 'package:future_of_workout/src/common.dart';
import 'package:future_of_workout/src/current_workout/current_workout.dart';
class FinishButton extends StatelessWidget {
const FinishButton({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: BarButton(
text: context.locale.finishWorkout,
icon: const AppIcon(iconData: AppIcons.stop),
onTap: () async {
final bloc = context.read<CurrentWorkoutBloc>();
await showDialog<bool>(
context: context,
builder: (builderContext) => ConfirmDialog(
title: context.locale.finishWorkout,
content: Text(
context.locale.finishWorkoutText,
style: AppTextStyle.medium16,
),
onConfirm: () => bloc.add(const CurrentWorkoutFinish()),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/bloc/current_workout_state.dart
|
part of 'current_workout_bloc.dart';
enum CurrentWorkoutStatus {
initial,
start,
started,
loading,
loaded,
rest,
restComplete,
finish,
failure,
}
class CurrentWorkoutState extends Equatable {
const CurrentWorkoutState({
this.status = CurrentWorkoutStatus.initial,
this.workoutLog,
this.workoutExerciseId,
this.time = 0,
this.restDuration,
});
final CurrentWorkoutStatus status;
final WorkoutLog? workoutLog;
final String? workoutExerciseId;
final int time;
final int? restDuration;
@override
List<Object?> get props => [status, workoutLog, time, restDuration];
CurrentWorkoutState copyWith({
CurrentWorkoutStatus? status,
WorkoutLog? workoutLog,
String? workoutExerciseId,
int? time,
int? Function()? restDuration,
}) {
return CurrentWorkoutState(
status: status ?? this.status,
workoutLog: workoutLog ?? this.workoutLog,
workoutExerciseId: workoutExerciseId ?? this.workoutExerciseId,
time: time ?? this.time,
restDuration: restDuration != null ? restDuration() : this.restDuration,
);
}
@override
String toString() {
final map = {
'status': status,
// 'workoutLog': workoutLog,
'time': time,
'restDuration': restDuration,
};
return map.toString();
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/bloc/current_workout_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:future_of_workout/src/shared/shared.dart';
import 'package:workout_log_repository/workout_log_repository.dart';
import 'package:workout_repository/workout_repository.dart';
part 'current_workout_event.dart';
part 'current_workout_state.dart';
class CurrentWorkoutBloc
extends Bloc<CurrentWorkoutEvent, CurrentWorkoutState> {
CurrentWorkoutBloc({
required WorkoutRepository workoutRepository,
required WorkoutLogRepository workoutLogRepository,
}) : _workoutRepository = workoutRepository,
_workoutLogRepository = workoutLogRepository,
_ticker = const Ticker(),
super(const CurrentWorkoutState()) {
on<CurrentWorkoutStartWorkout>(_onStartWorkout);
on<CurrentWorkoutSubscriptionRequested>(_onSubscriptionRequested);
on<CurrentWorkoutFinish>(_onFinish);
on<CurrentWorkoutClear>(_onClear);
on<CurrentWorkoutTicked>(_onTicked);
on<CurrentWorkoutAdd>(_onAdd);
on<CurrentWorkoutRestStarted>(_onRestStarted);
on<CurrentWorkoutRestStop>(_onRestStop);
on<CurrentWorkoutRestTicked>(_onRestTicked);
on<CurrentWorkoutRestAdd>(_onRestAdd);
on<CurrentWorkoutRestSubtract>(_onRestSubtract);
on<CurrentWorkoutReorder>(_onReorder);
}
final WorkoutRepository _workoutRepository;
final WorkoutLogRepository _workoutLogRepository;
final Ticker _ticker;
StreamSubscription<int>? _tickerSubscription;
StreamSubscription<int>? _restTickerSubscription;
@override
Future<void> close() {
_tickerSubscription?.cancel();
_restTickerSubscription?.cancel();
return super.close();
}
Future<void> _onStartWorkout(
CurrentWorkoutStartWorkout event,
Emitter<CurrentWorkoutState> emit,
) async {
emit(state.copyWith(status: CurrentWorkoutStatus.start));
WorkoutLog workoutLog;
if (event.id == null) {
workoutLog = WorkoutLog();
} else {
final plan = _workoutRepository.getPlan(id: event.id!);
final workout =
plan.workouts.firstWhere((element) => element.id == event.workoutId);
workoutLog = state.workoutLog == null
? WorkoutLog.fromWorkout(workout)
: state.workoutLog!.copyWith(
workoutExerciseLogs: state.workoutLog!.workoutExerciseLogs +
WorkoutLog.fromWorkout(workout).workoutExerciseLogs,
);
}
await _workoutLogRepository.saveWorkoutLog(workoutLog: workoutLog);
emit(state.copyWith(status: CurrentWorkoutStatus.started));
add(const CurrentWorkoutSubscriptionRequested());
}
Future<void> _onSubscriptionRequested(
CurrentWorkoutSubscriptionRequested event,
Emitter<CurrentWorkoutState> emit,
) async {
emit(state.copyWith(status: CurrentWorkoutStatus.loading));
await emit.forEach<WorkoutLog?>(
_workoutLogRepository.getCurrentWorkout(),
onData: (workoutLog) {
if (workoutLog != null) {
_listenTickerSubscription(startDate: workoutLog.startDate);
return state.copyWith(
status: CurrentWorkoutStatus.loaded,
workoutLog: workoutLog,
);
}
return state.copyWith(
status: CurrentWorkoutStatus.initial,
);
},
onError: (_, __) => state.copyWith(
status: CurrentWorkoutStatus.failure,
),
);
}
void _listenTickerSubscription({required DateTime startDate}) {
_tickerSubscription?.cancel();
final duration = DateTime.now().difference(startDate);
_tickerSubscription = _ticker.tick(time: duration.inSeconds).listen((time) {
add(CurrentWorkoutTicked(time: time));
});
}
Future<void> _onFinish(
CurrentWorkoutFinish event,
Emitter<CurrentWorkoutState> emit,
) async {
final workoutLog = state.workoutLog!.copyWith(endDate: DateTime.now());
if (workoutLog.workoutExerciseLogs.any(
(exercise) =>
exercise.exerciseSeriesLogs.any((series) => series.isFinished),
)) {
await _workoutLogRepository.saveWorkoutLog(workoutLog: workoutLog);
} else {
await _workoutLogRepository.deleteWorkoutLog(id: workoutLog.id);
}
await _tickerSubscription?.cancel();
await _restTickerSubscription?.cancel();
emit(
state.copyWith(
status: CurrentWorkoutStatus.finish,
workoutLog: workoutLog,
),
);
}
Future<void> _onClear(
CurrentWorkoutClear event,
Emitter<CurrentWorkoutState> emit,
) async {
emit(const CurrentWorkoutState());
}
void _onTicked(
CurrentWorkoutTicked event,
Emitter<CurrentWorkoutState> emit,
) {
emit(state.copyWith(time: event.time));
}
Future<void> _onAdd(
CurrentWorkoutAdd event,
Emitter<CurrentWorkoutState> emit,
) async {
final log = state.workoutLog!;
final exercises = List.of(log.workoutExerciseLogs);
for (final exercise in event.exercises) {
final item = WorkoutExerciseLog.fromWorkoutExercise(
WorkoutExercise(
index: exercises.length,
exercise: exercise,
),
);
exercises.add(item);
}
final workout = log.copyWith(workoutExerciseLogs: exercises);
await _workoutLogRepository.saveWorkoutLog(workoutLog: workout);
emit(state.copyWith(workoutLog: workout));
}
void _onRestStarted(
CurrentWorkoutRestStarted event,
Emitter<CurrentWorkoutState> emit,
) {
emit(
state.copyWith(
status: CurrentWorkoutStatus.rest,
restDuration: () => event.restDuration,
workoutExerciseId: event.workoutExerciseId,
),
);
_restTickerSubscription?.cancel();
_restTickerSubscription =
_ticker.countdown(time: event.restDuration).listen((duration) {
add(CurrentWorkoutRestTicked(restDuration: duration));
});
}
FutureOr<void> _onRestStop(
CurrentWorkoutRestStop event,
Emitter<CurrentWorkoutState> emit,
) {
_restTickerSubscription?.cancel();
emit(
state.copyWith(
restDuration: () => null,
status: CurrentWorkoutStatus.restComplete,
),
);
}
void _onRestTicked(
CurrentWorkoutRestTicked event,
Emitter<CurrentWorkoutState> emit,
) {
emit(
event.restDuration > 0
? state.copyWith(restDuration: () => event.restDuration)
: state.copyWith(
restDuration: () => null,
status: CurrentWorkoutStatus.restComplete,
),
);
}
FutureOr<void> _onRestAdd(
CurrentWorkoutRestAdd event,
Emitter<CurrentWorkoutState> emit,
) {
add(
CurrentWorkoutRestStarted(
restDuration: state.restDuration! + 15,
workoutExerciseId: state.workoutExerciseId!,
),
);
}
FutureOr<void> _onRestSubtract(
CurrentWorkoutRestSubtract event,
Emitter<CurrentWorkoutState> emit,
) {
final duration = (state.restDuration! - 15).clamp(1, 999);
add(
CurrentWorkoutRestStarted(
restDuration: duration,
workoutExerciseId: state.workoutExerciseId!,
),
);
}
Future<void> _onReorder(
CurrentWorkoutReorder event,
Emitter<CurrentWorkoutState> emit,
) async {
final log = state.workoutLog!;
final list = List.of(log.workoutExerciseLogs);
final exercise = list.removeAt(event.oldIndex);
final index =
event.newIndex > event.oldIndex ? event.newIndex - 1 : event.newIndex;
list.insert(index, exercise);
final workout = log.copyWith(workoutExerciseLogs: list);
await _workoutLogRepository.saveWorkoutLog(workoutLog: workout);
emit(state.copyWith(workoutLog: workout));
}
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout/bloc/current_workout_event.dart
|
part of 'current_workout_bloc.dart';
abstract class CurrentWorkoutEvent extends Equatable {
const CurrentWorkoutEvent();
@override
List<Object?> get props => [];
}
class CurrentWorkoutStartWorkout extends CurrentWorkoutEvent {
const CurrentWorkoutStartWorkout({this.id, this.workoutId});
final String? id;
final String? workoutId;
@override
List<Object?> get props => [id, workoutId];
}
class CurrentWorkoutSubscriptionRequested extends CurrentWorkoutEvent {
const CurrentWorkoutSubscriptionRequested();
}
class CurrentWorkoutFinish extends CurrentWorkoutEvent {
const CurrentWorkoutFinish();
}
class CurrentWorkoutClear extends CurrentWorkoutEvent {
const CurrentWorkoutClear();
}
class CurrentWorkoutTicked extends CurrentWorkoutEvent {
const CurrentWorkoutTicked({required this.time});
final int time;
@override
List<Object?> get props => [time];
}
class CurrentWorkoutAdd extends CurrentWorkoutEvent {
const CurrentWorkoutAdd({required this.exercises});
final List<Exercise> exercises;
@override
List<Object?> get props => exercises;
}
class CurrentWorkoutRestStarted extends CurrentWorkoutEvent {
const CurrentWorkoutRestStarted({
required this.restDuration,
required this.workoutExerciseId,
});
final int restDuration;
final String workoutExerciseId;
@override
List<Object> get props => [restDuration, workoutExerciseId];
}
class CurrentWorkoutRestStop extends CurrentWorkoutEvent {
const CurrentWorkoutRestStop();
}
class CurrentWorkoutRestAdd extends CurrentWorkoutEvent {
const CurrentWorkoutRestAdd({required this.value});
final int value;
@override
List<Object?> get props => [value];
}
class CurrentWorkoutRestSubtract extends CurrentWorkoutEvent {
const CurrentWorkoutRestSubtract({required this.value});
final int value;
@override
List<Object?> get props => [value];
}
class CurrentWorkoutRestTicked extends CurrentWorkoutEvent {
const CurrentWorkoutRestTicked({required this.restDuration});
final int restDuration;
@override
List<Object> get props => [restDuration];
}
class CurrentWorkoutReorder extends CurrentWorkoutEvent {
const CurrentWorkoutReorder({required this.oldIndex, required this.newIndex});
final int oldIndex;
final int newIndex;
@override
List<Object?> get props => [oldIndex, newIndex];
}
| 0
|
mirrored_repositories/future_of_workout/lib/src/current_workout
|
mirrored_repositories/future_of_workout/lib/src/current_workout/current_workout_summary/current_wokrout_summary.dart
|
export 'view/view.dart';
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.