Skip to content

An open-source cross-platform alternative to AirDrop

feat: receive options

Tien Do Nam9255d4e2f63b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f931758c..3ece936f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,8 @@
## 1.5.0 (2023-01-)
+- feat: allow accepting requests partially
+- feat: allow setting destination directory during accept phase
+- feat: allow renaming incoming files
- feat: keep screen on during file transfer
## 1.4.0 (2023-01-06)
diff --git a/assets/i18n/strings.i18n.json b/assets/i18n/strings.i18n.json
index 74457545..e538edb8 100644
--- a/assets/i18n/strings.i18n.json
+++ b/assets/i18n/strings.i18n.json
@@ -15,6 +15,7 @@
"edit": "Edit",
"error": "Error",
"example": "Example",
+ "files": "Files",
"finished": "Finished",
"hide": "Hide",
"no": "No",
@@ -22,11 +23,14 @@
"online": "Online",
"open": "Open",
"queue": "Queue",
+ "renamed": "Umbenannt",
+ "reset": "Reset",
"restart": "Restart",
"skipped": "Skipped",
"start": "Start",
"stop": "Stop",
"save": "Save",
+ "unchanged": "Unchanged",
"unknown": "Unknown",
"yes": "Yes"
},
@@ -98,6 +102,10 @@
"subTitleLink": "sent you a link:",
"canceled": "The sender has canceled the request."
},
+ "receiveOptionsPage": {
+ "title": "Options",
+ "destination": "@:settingsTab.receive.destination"
+ },
"sendPage": {
"waiting": "Waiting for response...",
"rejected": "The recipient has rejected the request."
@@ -125,21 +133,33 @@
"title": "Changelog"
},
"dialogs": {
- "noFiles": {
- "title": "No file selected",
- "content": "Please select at least one file."
+ "addressInput": {
+ "title": "Enter address",
+ "hashtag": "Hashtag",
+ "ip": "IP Address"
},
"cancelSession": {
"title": "Cancel file transfer",
"content": "Do you really want to cancel the file transfer?"
},
+ "fileNameInput": {
+ "title": "Enter file name",
+ "original": "Original: {original}"
+ },
"messageInput": {
"title": "Type message"
},
- "addressInput": {
- "title": "Enter address",
- "hashtag": "Hashtag",
- "ip": "IP Address"
+ "noFiles": {
+ "title": "No file selected",
+ "content": "Please select at least one file."
+ },
+ "quickActions": {
+ "title": "Quick Actions",
+ "counter": "Counter",
+ "prefix": "Prefix",
+ "padZero": "Pad with zeros",
+ "sortBeforeCount": "Sort alphabetically beforehand",
+ "random": "Random"
}
}
}
diff --git a/assets/i18n/strings_de.i18n.json b/assets/i18n/strings_de.i18n.json
index 2a914267..23b01f62 100644
--- a/assets/i18n/strings_de.i18n.json
+++ b/assets/i18n/strings_de.i18n.json
@@ -15,6 +15,7 @@
"edit": "Bearbeiten",
"error": "Fehler",
"example": "Beispiel",
+ "files": "Dateien",
"finished": "Abgeschlossen",
"hide": "Verstecken",
"no": "Nein",
@@ -22,11 +23,14 @@
"online": "Online",
"open": "Öffnen",
"queue": "Warteschlange",
+ "renamed": "Umbenannt",
+ "reset": "Zurücksetzen",
"restart": "Neustarten",
"skipped": "Übersprungen",
"start": "Start",
"stop": "Stop",
"save": "Speichern",
+ "unchanged": "Unverändert",
"unknown": "Unbekannt",
"yes": "Ja"
},
@@ -98,6 +102,10 @@
"subTitleLink": "sendet dir einen Link:",
"canceled": "Der Absender hat die Anfrage abgebrochen."
},
+ "receiveOptionsPage": {
+ "title": "Optionen",
+ "destination": "@:settingsTab.receive.destination"
+ },
"sendPage": {
"waiting": "Warte auf Antwort...",
"rejected": "Der Empfänger hat die Anfrage abgelehnt."
@@ -125,21 +133,33 @@
"title": "Changelog"
},
"dialogs": {
- "noFiles": {
- "title": "Keine Datei ausgewählt",
- "content": "Bitte wähle mindestens eine Datei aus."
+ "addressInput": {
+ "title": "Adresse eingeben",
+ "hashtag": "Hashtag",
+ "ip": "IP-Adresse"
},
"cancelSession": {
"title": "Dateiübertragung abbrechen",
"content": "Möchtest du wirklich die Dateiübertragung abbrechen?"
},
+ "fileNameInput": {
+ "title": "Dateiname eingeben",
+ "original": "Original: {original}"
+ },
"messageInput": {
"title": "Nachricht eingeben"
},
- "addressInput": {
- "title": "Adresse eingeben",
- "hashtag": "Hashtag",
- "ip": "IP-Adresse"
+ "noFiles": {
+ "title": "Keine Datei ausgewählt",
+ "content": "Bitte wähle mindestens eine Datei aus."
+ },
+ "quickActions": {
+ "title": "Quick Actions",
+ "counter": "Zähler",
+ "prefix": "Prefix",
+ "padZero": "Mit Nullen auffüllen",
+ "sortBeforeCount": "Vorher alphabetisch sortieren",
+ "random": "Zufall"
}
}
}
diff --git a/lib/init.dart b/lib/init.dart
index e703e658..a6c0ecf4 100644
--- a/lib/init.dart
+++ b/lib/init.dart
@@ -7,7 +7,7 @@ import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/pages/home_page.dart';
import 'package:localsend_app/provider/network/server_provider.dart';
import 'package:localsend_app/provider/persistence_provider.dart';
-import 'package:localsend_app/provider/selected_files_provider.dart';
+import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/util/platform_check.dart';
@@ -80,9 +80,9 @@ Future<void> postInit(BuildContext context, WidgetRef ref, void Function(int) go
void _handleSharedIntent(SharedMedia payload, WidgetRef ref) {
final message = payload.content;
if (message != null && message.trim().isNotEmpty) {
- ref.read(selectedFilesProvider.notifier).addMessage(message);
+ ref.read(selectedSendingFilesProvider.notifier).addMessage(message);
}
- ref.read(selectedFilesProvider.notifier).addFiles(
+ ref.read(selectedSendingFilesProvider.notifier).addFiles(
files: payload.attachments?.where((a) => a != null).cast<SharedAttachment>() ?? <SharedAttachment>[],
converter: CrossFileConverters.convertSharedAttachment,
);
diff --git a/lib/model/cross_file.dart b/lib/model/cross_file.dart
index 0ed1f20f..414a8b66 100644
--- a/lib/model/cross_file.dart
+++ b/lib/model/cross_file.dart
@@ -5,6 +5,7 @@ import 'package:wechat_assets_picker/wechat_assets_picker.dart';
part 'cross_file.freezed.dart';
/// Common file model to avoid any third party libraries in the core logic.
+/// This model is used during the file selection phase.
@freezed
class CrossFile with _$CrossFile {
const factory CrossFile({
diff --git a/lib/model/server/receive_state.dart b/lib/model/server/receive_state.dart
index 8921fbcb..f9f782db 100644
--- a/lib/model/server/receive_state.dart
+++ b/lib/model/server/receive_state.dart
@@ -16,6 +16,9 @@ class ReceiveState with _$ReceiveState {
required int? startTime,
required int? endTime,
required String destinationDirectory,
- required StreamController<bool>? responseHandler, // use this to accept / decline the request
+
+ // use this to accept / decline the request, empty map == decline
+ // FileId -> File Name
+ required StreamController<Map<String, String>?>? responseHandler,
}) = _ReceiveState;
}
diff --git a/lib/model/server/receiving_file.dart b/lib/model/server/receiving_file.dart
index 91e19622..828610e4 100644
--- a/lib/model/server/receiving_file.dart
+++ b/lib/model/server/receiving_file.dart
@@ -10,6 +10,7 @@ class ReceivingFile with _$ReceivingFile {
required FileDto file,
required FileStatus status,
required String? token,
+ required String? desiredName, // not null when accepted
required String? path, // when finished
required bool savedToGallery, // when finished
}) = _ReceivingFile;
diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart
index 54f05513..41655eac 100644
--- a/lib/pages/home_page.dart
+++ b/lib/pages/home_page.dart
@@ -6,7 +6,7 @@ import 'package:localsend_app/init.dart';
import 'package:localsend_app/pages/tabs/receive_tab.dart';
import 'package:localsend_app/pages/tabs/send_tab.dart';
import 'package:localsend_app/pages/tabs/settings_tab.dart';
-import 'package:localsend_app/provider/selected_files_provider.dart';
+import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/widget/responsive_list_view.dart';
import 'package:responsive_builder/responsive_builder.dart';
@@ -76,7 +76,7 @@ class _HomePageState extends ConsumerState<HomePage> {
});
},
onDragDone: (event) {
- ref.read(selectedFilesProvider.notifier).addFiles(
+ ref.read(selectedSendingFilesProvider.notifier).addFiles(
files: event.files,
converter: CrossFileConverters.convertXFile,
);
diff --git a/lib/pages/progress_page.dart b/lib/pages/progress_page.dart
index 3740ce26..f07b64c3 100644
--- a/lib/pages/progress_page.dart
+++ b/lib/pages/progress_page.dart
@@ -124,18 +124,23 @@ class _ProgressPageState extends ConsumerState<ProgressPage> {
itemBuilder: (context, index) {
if (index == 0) {
// title
- return Text(
- receiveState != null ? t.progressPage.titleReceiving : t.progressPage.titleSending,
- style: Theme.of(context).textTheme.headline6,
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 5),
+ child: Text(
+ receiveState != null ? t.progressPage.titleReceiving : t.progressPage.titleSending,
+ style: Theme.of(context).textTheme.headline6,
+ ),
);
}
final file = _files[index - 1];
+ final String fileName = receiveState?.files[file.id]?.desiredName ?? file.fileName;
+
final fileStatus = receiveState?.files[file.id]?.status ?? sendState!.files[file.id]!.status;
final savedToGallery = receiveState?.files[file.id]?.savedToGallery ?? false;
return Padding(
- padding: const EdgeInsets.symmetric(vertical: 10),
+ padding: const EdgeInsets.symmetric(vertical: 5),
child: InkWell(
splashColor: Colors.transparent,
splashFactory: NoSplash.splashFactory,
@@ -157,7 +162,7 @@ class _ProgressPageState extends ConsumerState<ProgressPage> {
children: [
Flexible(
child: Text(
- file.fileName,
+ fileName,
style: const TextStyle(fontSize: 16),
maxLines: 1,
overflow: TextOverflow.ellipsis,
diff --git a/lib/pages/receive_options_page.dart b/lib/pages/receive_options_page.dart
new file mode 100644
index 00000000..d4edef45
--- /dev/null
+++ b/lib/pages/receive_options_page.dart
@@ -0,0 +1,176 @@
+import 'package:file_picker/file_picker.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:localsend_app/gen/strings.g.dart';
+import 'package:localsend_app/provider/network/server_provider.dart';
+import 'package:localsend_app/provider/selection/selected_receiving_files_provider.dart';
+import 'package:localsend_app/util/file_size_helper.dart';
+import 'package:localsend_app/widget/dialogs/file_name_input_dialog.dart';
+import 'package:localsend_app/widget/dialogs/quick_actions_dialog.dart';
+import 'package:localsend_app/widget/responsive_list_view.dart';
+
+class ReceiveOptionsPage extends ConsumerStatefulWidget {
+ const ReceiveOptionsPage({Key? key}) : super(key: key);
+
+ @override
+ ConsumerState<ReceiveOptionsPage> createState() => _ReceiveOptionsPageState();
+}
+
+class _ReceiveOptionsPageState extends ConsumerState<ReceiveOptionsPage> {
+ @override
+ Widget build(BuildContext context) {
+ final receiveState = ref.watch(serverProvider.select((s) => s?.receiveState));
+ if (receiveState == null) {
+ return Scaffold(
+ body: Container(),
+ );
+ }
+ final selectState = ref.watch(selectedReceivingFilesProvider);
+
+ return Scaffold(
+ appBar: AppBar(
+ title: Text(t.receiveOptionsPage.title),
+ ),
+ body: ResponsiveListView(
+ padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 20),
+ children: [
+ Row(
+ children: [
+ Text(t.receiveOptionsPage.destination, style: Theme.of(context).textTheme.headline6),
+ const SizedBox(width: 10),
+ TextButton(
+ style: TextButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.onSurface,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ minimumSize: Size.zero,
+ shape: const CircleBorder(),
+ ),
+ onPressed: () async {
+ final directory = await FilePicker.platform.getDirectoryPath();
+ if (directory != null) {
+ ref.read(serverProvider.notifier).setSessionDestinationDir(directory);
+ }
+ },
+ child: const Icon(Icons.edit),
+ ),
+ ],
+ ),
+ const SizedBox(height: 5),
+ Text(receiveState.destinationDirectory),
+ const SizedBox(height: 20),
+ Row(
+ children: [
+ Text(t.general.files, style: Theme.of(context).textTheme.headline6),
+ const SizedBox(width: 10),
+ Tooltip(
+ message: t.dialogs.quickActions.title,
+ child: TextButton(
+ style: TextButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.onSurface,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ minimumSize: Size.zero,
+ shape: const CircleBorder(),
+ ),
+ onPressed: () {
+ showDialog(context: context, builder: (_) => const QuickActionsDialog());
+ },
+ child: const Icon(Icons.tips_and_updates),
+ ),
+ ),
+ const SizedBox(width: 10),
+ Tooltip(
+ message: t.general.reset,
+ child: TextButton(
+ style: TextButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.onSurface,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ minimumSize: Size.zero,
+ shape: const CircleBorder(),
+ ),
+ onPressed: () async {
+ ref.read(selectedReceivingFilesProvider.notifier).init(receiveState.files.values.map((f) => f.file).toList());
+ },
+ child: const Icon(Icons.undo),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 5),
+ ...receiveState.files.values.map((file) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 10),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Icon(file.file.fileType.icon, size: 46),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ selectState[file.file.id] ?? file.file.fileName,
+ style: const TextStyle(fontSize: 16),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ Text(
+ '${!selectState.containsKey(file.file.id)
+ ? t.general.skipped
+ : (selectState[file.file.id] == file.file.fileName ? t.general.unchanged : t.general.renamed)} - ${file.file.size.asReadableFileSize}',
+ style: TextStyle(
+ color: !selectState.containsKey(file.file.id)
+ ? Colors.grey
+ : (selectState[file.file.id] == file.file.fileName
+ ? Theme.of(context).colorScheme.tertiaryContainer
+ : Colors.orange)),
+ )
+ ],
+ ),
+ ),
+ Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TextButton(
+ style: TextButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.onSurface,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ minimumSize: Size.zero,
+ shape: const CircleBorder(),
+ ),
+ onPressed: selectState[file.file.id] == null ? null : () async {
+ final result = await showDialog<String>(
+ context: context,
+ builder: (_) => FileNameInputDialog(
+ originalName: file.file.fileName,
+ initialName: selectState[file.file.id]!,
+ ),
+ );
+ if (result != null) {
+ ref.read(selectedReceivingFilesProvider.notifier).rename(file.file.id, result);
+ }
+ },
+ child: const Icon(Icons.edit),
+ ),
+ Checkbox(
+ value: selectState.containsKey(file.file.id),
+ activeColor: Theme.of(context).colorScheme.onSurface,
+ onChanged: (selected) {
+ if (selected == true) {
+ ref.read(selectedReceivingFilesProvider.notifier).select(file.file);
+ } else {
+ ref.read(selectedReceivingFilesProvider.notifier).unselect(file.file.id);
+ }
+ },
+ ),
+ ],
+ ),
+ ],
+ ),
+ );
+ }),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/pages/receive_page.dart b/lib/pages/receive_page.dart
index d96470e8..d04adaf0 100644
--- a/lib/pages/receive_page.dart
+++ b/lib/pages/receive_page.dart
@@ -6,7 +6,9 @@ import 'package:localsend_app/model/file_type.dart';
import 'package:localsend_app/model/server/receive_state.dart';
import 'package:localsend_app/model/session_status.dart';
import 'package:localsend_app/pages/progress_page.dart';
+import 'package:localsend_app/pages/receive_options_page.dart';
import 'package:localsend_app/provider/network/server_provider.dart';
+import 'package:localsend_app/provider/selection/selected_receiving_files_provider.dart';
import 'package:localsend_app/util/ip_helper.dart';
import 'package:localsend_app/util/platform_check.dart';
import 'package:localsend_app/util/snackbar.dart';
@@ -15,15 +17,45 @@ import 'package:localsend_app/widget/responsive_list_view.dart';
import 'package:routerino/routerino.dart';
import 'package:url_launcher/url_launcher.dart';
-class ReceivePage extends ConsumerWidget {
+class ReceivePage extends ConsumerStatefulWidget {
const ReceivePage({Key? key}) : super(key: key);
+ @override
+ ConsumerState<ReceivePage> createState() => _ReceivePageState();
+}
+
+class _ReceivePageState extends ConsumerState<ReceivePage> {
+ String? _message;
+ bool _isLink = false;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) => _init());
+ }
+
+ Future<void> _init() async {
+ final receiveState = ref.watch(serverProvider)?.receiveState;
+ if (receiveState == null) {
+ return;
+ }
+
+ ref.read(selectedReceivingFilesProvider.notifier).init(receiveState.files.values.map((f) => f.file).toList());
+ setState(() {
+ final firstFile = receiveState.files.values.first.file;
+ // show message if there is only one text file
+ _message = receiveState.files.length == 1 && firstFile.fileType == FileType.text && firstFile.preview != null ? firstFile.preview : null;
+ _isLink = _message != null && (_message!.startsWith('http://') || _message!.startsWith('https'));
+ });
+ }
+
void _acceptNothing(WidgetRef ref, ReceiveState receiveState) {
ref.read(serverProvider.notifier).acceptFileRequest({});
}
- void _acceptAll(WidgetRef ref, ReceiveState receiveState) {
- ref.read(serverProvider.notifier).acceptFileRequest(receiveState.files.values.map((f) => f.file.id).toSet());
+ void _accept(WidgetRef ref, ReceiveState receiveState) {
+ final selectedFiles = ref.read(selectedReceivingFilesProvider);
+ ref.read(serverProvider.notifier).acceptFileRequest(selectedFiles);
}
void _decline(WidgetRef ref) {
@@ -31,7 +63,7 @@ class ReceivePage extends ConsumerWidget {
}
@override
- Widget build(BuildContext context, WidgetRef ref) {
+ Widget build(BuildContext context) {
final receiveState = ref.watch(serverProvider)?.receiveState;
if (receiveState == null) {
// when declining/accepting the request, there is a short frame where tempRequest is null
@@ -39,11 +71,7 @@ class ReceivePage extends ConsumerWidget {
body: Container(),
);
}
-
- final firstFile = receiveState.files.values.first.file;
- // show message if there is only one text file
- final message = receiveState.files.length == 1 && firstFile.fileType == FileType.text && firstFile.preview != null ? firstFile.preview : null;
- final isLink = message != null && (message.startsWith('http://') || message.startsWith('https'));
+ final selectedFiles = ref.watch(selectedReceivingFilesProvider);
return WillPopScope(
onWillPop: () async {
@@ -58,7 +86,7 @@ class ReceivePage extends ConsumerWidget {
child: Builder(
builder: (context) {
final height = MediaQuery.of(context).size.height;
- final smallUi = message != null && height < 600;
+ final smallUi = _message != null && height < 600;
return Padding(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: smallUi ? 20 : 30),
child: Column(
@@ -99,11 +127,11 @@ class ReceivePage extends ConsumerWidget {
),
const SizedBox(height: 40),
Text(
- message != null ? (isLink ? t.receivePage.subTitleLink : t.receivePage.subTitleMessage) : t.receivePage.subTitle(n: receiveState.files.length),
+ _message != null ? (_isLink ? t.receivePage.subTitleLink : t.receivePage.subTitleMessage) : t.receivePage.subTitle(n: receiveState.files.length),
style: smallUi ? null : Theme.of(context).textTheme.headline6,
textAlign: TextAlign.center,
),
- if (message != null)
+ if (_message != null)
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -116,7 +144,7 @@ class ReceivePage extends ConsumerWidget {
child: Padding(
padding: const EdgeInsets.all(10),
child: SelectableText(
- message,
+ _message!,
),
),
),
@@ -129,14 +157,14 @@ class ReceivePage extends ConsumerWidget {
children: [
ElevatedButton(
onPressed: () {
- Clipboard.setData(ClipboardData(text: message));
+ Clipboard.setData(ClipboardData(text: _message));
if (checkPlatformIsDesktop()) {
context.showSnackBar(t.general.copiedToClipboard);
}
},
child: Text(t.general.copy),
),
- if (isLink)
+ if (_isLink)
Padding(
padding: const EdgeInsets.only(left: 20),
child: ElevatedButton(
@@ -145,7 +173,7 @@ class ReceivePage extends ConsumerWidget {
foregroundColor: Theme.of(context).buttonTheme.colorScheme!.onPrimary,
),
onPressed: () {
- launchUrl(Uri.parse(message));
+ launchUrl(Uri.parse(_message!));
},
child: Text(t.general.open),
),
@@ -157,6 +185,19 @@ class ReceivePage extends ConsumerWidget {
],
),
),
+ if (receiveState.status == SessionStatus.waiting && _message == null)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 20),
+ child: TextButton(
+ style: TextButton.styleFrom(
+ foregroundColor: Theme.of(context).colorScheme.onSurface,
+ ),
+ onPressed: () {
+ context.push(() => const ReceiveOptionsPage());
+ },
+ child: Text(t.receiveOptionsPage.title),
+ ),
+ ),
if (receiveState.status == SessionStatus.canceledBySender)
...[
Padding(
@@ -174,7 +215,7 @@ class ReceivePage extends ConsumerWidget {
),
),
]
- else if (message != null)
+ else if (_message != null)
Center(
child: TextButton.icon(
style: TextButton.styleFrom(
@@ -210,8 +251,8 @@ class ReceivePage extends ConsumerWidget {
backgroundColor: Theme.of(context).buttonTheme.colorScheme!.primary,
foregroundColor: Theme.of(context).buttonTheme.colorScheme!.onPrimary,
),
- onPressed: () {
- _acceptAll(ref, receiveState);
+ onPressed: selectedFiles.isEmpty ? null : () {
+ _accept(ref, receiveState);
context.pushAndRemoveUntilImmediately(
removeUntil: ReceivePage,
builder: () => const ProgressPage(),
diff --git a/lib/pages/selected_files_page.dart b/lib/pages/selected_files_page.dart
index e208911b..8b1bd9f8 100644
--- a/lib/pages/selected_files_page.dart
+++ b/lib/pages/selected_files_page.dart
@@ -5,7 +5,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/file_type.dart';
-import 'package:localsend_app/provider/selected_files_provider.dart';
+import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/util/file_size_helper.dart';
import 'package:localsend_app/widget/file_thumbnail.dart';
import 'package:localsend_app/widget/responsive_list_view.dart';
@@ -16,7 +16,7 @@ class SelectedFilesPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
- final selectedFiles = ref.watch(selectedFilesProvider);
+ final selectedFiles = ref.watch(selectedSendingFilesProvider);
return Scaffold(
appBar: AppBar(
@@ -39,7 +39,7 @@ class SelectedFilesPage extends ConsumerWidget {
),
ElevatedButton(
onPressed: () {
- ref.read(selectedFilesProvider.notifier).reset();
+ ref.read(selectedSendingFilesProvider.notifier).reset();
context.popUntilRoot();
},
child: Text(t.selectedFilesPage.deleteAll),
@@ -76,8 +76,8 @@ class SelectedFilesPage extends ConsumerWidget {
TextButton(
style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onSurface),
onPressed: () {
- final currCount = ref.read(selectedFilesProvider).length;
- ref.read(selectedFilesProvider.notifier).removeAt(index);
+ final currCount = ref.read(selectedSendingFilesProvider).length;
+ ref.read(selectedSendingFilesProvider.notifier).removeAt(index);
if (currCount == 1) {
context.popUntilRoot();
}
diff --git a/lib/pages/tabs/send_tab.dart b/lib/pages/tabs/send_tab.dart
index 7ca73552..24d9756d 100644
--- a/lib/pages/tabs/send_tab.dart
+++ b/lib/pages/tabs/send_tab.dart
@@ -8,7 +8,7 @@ import 'package:localsend_app/provider/device_info_provider.dart';
import 'package:localsend_app/provider/network/nearby_devices_provider.dart';
import 'package:localsend_app/provider/network/send_provider.dart';
import 'package:localsend_app/provider/network_info_provider.dart';
-import 'package:localsend_app/provider/selected_files_provider.dart';
+import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/file_picker.dart';
import 'package:localsend_app/util/file_size_helper.dart';
@@ -55,7 +55,7 @@ class _SendTabState extends ConsumerState<SendTab> {
@override
Widget build(BuildContext context) {
- final selectedFiles = ref.watch(selectedFilesProvider);
+ final selectedFiles = ref.watch(selectedSendingFilesProvider);
final networkInfo = ref.watch(networkInfoProvider);
final myDevice = ref.watch(deviceInfoProvider);
final nearbyDevicesState = ref.watch(nearbyDevicesProvider);
@@ -215,7 +215,7 @@ class _SendTabState extends ConsumerState<SendTab> {
shape: const CircleBorder(),
),
onPressed: () async {
- final files = ref.read(selectedFilesProvider);
+ final files = ref.read(selectedSendingFilesProvider);
if (files.isEmpty) {
context.pushBottomSheet(() => const NoFilesDialog());
return;
@@ -292,7 +292,7 @@ class _SendTabState extends ConsumerState<SendTab> {
child: DeviceListTile(
device: device,
onTap: () {
- final files = ref.read(selectedFilesProvider);
+ final files = ref.read(selectedSendingFilesProvider);
if (files.isEmpty) {
context.pushBottomSheet(() => const NoFilesDialog());
return;
diff --git a/lib/provider/dio_provider.dart b/lib/provider/dio_provider.dart
index cc46427c..ca89d77d 100644
--- a/lib/provider/dio_provider.dart
+++ b/lib/provider/dio_provider.dart
@@ -4,16 +4,25 @@ import 'package:dio/dio.dart';
import 'package:dio/adapter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
+enum DioType {
+ discovery(2000),
+ longLiving(30 * 24 * 60 * 60 * 1000); // assuming someone sends a large file over several days
+
+ const DioType(this.timeout);
+
+ final int timeout;
+}
+
/// Provides a dio having a specific timeout.
///
/// It always trust the self signed certificate as all requests happen in a local network.
/// The user only needs to trust the local IP address.
/// Thanks to TCP (HTTP uses TCP), IP spoofing is nearly impossible.
-final dioProvider = Provider.family<Dio, int>((ref, timeout) {
+final dioProvider = Provider.family<Dio, DioType>((ref, type) {
final dio = Dio(
BaseOptions(
- connectTimeout: timeout,
- sendTimeout: timeout,
+ connectTimeout: type.timeout,
+ sendTimeout: type.timeout,
),
);
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) {
diff --git a/lib/provider/network/nearby_devices_provider.dart b/lib/provider/network/nearby_devices_provider.dart
index 1a46925a..1e1b7c6a 100644
--- a/lib/provider/network/nearby_devices_provider.dart
+++ b/lib/provider/network/nearby_devices_provider.dart
@@ -8,7 +8,7 @@ import 'package:localsend_app/util/api_route_builder.dart';
import 'package:localsend_app/util/task_runner.dart';
final nearbyDevicesProvider = StateNotifierProvider<NearbyDevicesNotifier, NearbyDevicesState>((ref) {
- final dio = ref.watch(dioProvider(2000));
+ final dio = ref.watch(dioProvider(DioType.discovery));
return NearbyDevicesNotifier(dio);
});
diff --git a/lib/provider/network/send_provider.dart b/lib/provider/network/send_provider.dart
index d2bb701e..eb6e8581 100644
--- a/lib/provider/network/send_provider.dart
+++ b/lib/provider/network/send_provider.dart
@@ -38,8 +38,8 @@ class SendNotifier extends StateNotifier<SendState?> {
required Device target,
required List<CrossFile> files,
}) async {
- final requestDio = _ref.read(dioProvider(5 * 60 * 1000));
- final uploadDio = _ref.read(dioProvider(30 * 24 * 60 * 60 * 1000)); // assuming someone sends a large file over several days
+ final requestDio = _ref.read(dioProvider(DioType.longLiving));
+ final uploadDio = _ref.read(dioProvider(DioType.longLiving));
final cancelToken = CancelToken();
final requestState = SendState(
@@ -207,7 +207,7 @@ class SendNotifier extends StateNotifier<SendState?> {
state?.cancelToken?.cancel(); // cancel current request
state = null;
try {
- await _ref.read(dioProvider(2000)).post(ApiRoute.cancel.target(target));
+ await _ref.read(dioProvider(DioType.discovery)).post(ApiRoute.cancel.target(target));
} catch (_) {}
}
}
diff --git a/lib/provider/network/server_provider.dart b/lib/provider/network/server_provider.dart
index b191b289..c4232c83 100644
--- a/lib/provider/network/server_provider.dart
+++ b/lib/provider/network/server_provider.dart
@@ -69,10 +69,10 @@ class ServerNotifier extends StateNotifier<ServerState?> {
final securityContextResult = generateSecurityContext();
newServerState = ServerState(
- httpServer: await serve(router, '0.0.0.0', port, securityContext: SecurityContext()
- ..usePrivateKeyBytes(securityContextResult.privateKey.codeUnits)
- ..useCertificateChainBytes(securityContextResult.certificate.codeUnits)
- ),
+ httpServer: await serve(router, '0.0.0.0', port,
+ securityContext: SecurityContext()
+ ..usePrivateKeyBytes(securityContextResult.privateKey.codeUnits)
+ ..useCertificateChainBytes(securityContextResult.certificate.codeUnits)),
alias: alias,
port: port,
receiveState: null,
@@ -119,14 +119,14 @@ class ServerNotifier extends StateNotifier<ServerState?> {
case TargetPlatform.macOS:
case TargetPlatform.windows:
case TargetPlatform.fuchsia:
- destinationDir = (await path.getDownloadsDirectory())!.path;
+ destinationDir = (await path.getDownloadsDirectory())!.path.replaceAll('\\', '/');
break;
}
}
print('Destination Directory: $destinationDir');
- final streamController = StreamController<bool>();
+ final streamController = StreamController<Map<String, String>?>();
state = state!.copyWith(
receiveState: ReceiveState(
status: SessionStatus.waiting,
@@ -137,6 +137,7 @@ class ServerNotifier extends StateNotifier<ServerState?> {
file: file,
status: FileStatus.queue,
token: null,
+ desiredName: null,
path: null,
savedToGallery: false,
),
@@ -153,8 +154,14 @@ class ServerNotifier extends StateNotifier<ServerState?> {
// Delayed response (waiting for user's decision)
final result = await streamController.stream.first;
- if (result) {
- if (state!.receiveState!.files.values.every((file) => file.token == null)) {
+
+ if (state?.receiveState == null) {
+ // somehow this state is already disposed
+ return Response.internalServerError();
+ }
+
+ if (result != null) {
+ if (result.isEmpty) {
// nothing selected, send this to sender and close session
closeSession();
return Response.ok(
@@ -162,14 +169,33 @@ class ServerNotifier extends StateNotifier<ServerState?> {
headers: {'Content-Type': 'application/json'},
);
}
- state = state?.copyWith(
- receiveState: state?.receiveState?.copyWith(
+
+ final receiveState = state!.receiveState!;
+ state = state!.copyWith(
+ receiveState: receiveState.copyWith(
status: SessionStatus.sending,
+ files: Map.fromEntries(
+ receiveState.files.values.map((entry) {
+ final desiredName = result[entry.file.id];
+ return MapEntry(
+ entry.file.id,
+ ReceivingFile(
+ file: entry.file,
+ status: desiredName != null ? FileStatus.queue : FileStatus.skipped,
+ token: desiredName != null ? _uuid.v4() : null,
+ desiredName: desiredName,
+ path: null,
+ savedToGallery: false,
+ ),
+ );
+ }),
+ ),
+ responseHandler: null,
),
);
return Response.ok(
jsonEncode({
- for (final file in state!.receiveState!.files.values) file.file.id: file.token,
+ for (final file in state!.receiveState!.files.values.where((f) => f.token != null)) file.file.id: file.token,
}),
headers: {'Content-Type': 'application/json'});
} else {
@@ -203,20 +229,24 @@ class ServerNotifier extends StateNotifier<ServerState?> {
// begin of actual file transfer
state = state?.copyWith(
receiveState: receiveState.copyWith(
- files: {...receiveState.files}..update(fileId, (_) => receivingFile.copyWith(status: FileStatus.sending)),
+ files: {...receiveState.files}..update(fileId, (_) => receivingFile.copyWith(
+ status: FileStatus.sending,
+ token: null, // remove token to reject further uploads of the same file
+ )),
startTime: receiveState.startTime ?? DateTime.now().millisecondsSinceEpoch,
),
);
final destinationPath = await _digestFilePath(
dir: receiveState.destinationDirectory,
- fileName: receivingFile.file.fileName,
+ fileName: receivingFile.desiredName!,
);
print('Saving ${receivingFile.file.fileName} to $destinationPath');
try {
- final saveToGallery = checkPlatformWithGallery() && _ref.read(settingsProvider).saveToGallery &&
+ final saveToGallery = checkPlatformWithGallery() &&
+ _ref.read(settingsProvider).saveToGallery &&
(receivingFile.file.fileType == FileType.image || receivingFile.file.fileType == FileType.video);
await saveFile(
destinationPath: destinationPath,
@@ -291,35 +321,14 @@ class ServerNotifier extends StateNotifier<ServerState?> {
return await startServer(alias: alias, port: port);
}
- void acceptFileRequest(Set<String> fileIds) {
- final receiveState = state?.receiveState;
- if (receiveState == null) {
- return;
- }
-
- final responseHandler = receiveState.responseHandler;
- if (responseHandler == null) {
+ void acceptFileRequest(Map<String, String> fileNameMap) {
+ final controller = state?.receiveState?.responseHandler;
+ if (controller == null) {
return;
}
- state = state?.copyWith(
- receiveState: receiveState.copyWith(
- files: {
- for (final file in receiveState.files.values)
- file.file.id: ReceivingFile(
- file: file.file,
- status: fileIds.contains(file.file.id) ? FileStatus.queue : FileStatus.skipped,
- token: fileIds.contains(file.file.id) ? _uuid.v4() : null,
- path: null,
- savedToGallery: false,
- ),
- },
- responseHandler: null,
- ),
- );
-
- responseHandler.add(true);
- responseHandler.close();
+ controller.add(fileNameMap);
+ controller.close();
}
void declineFileRequest() {
@@ -328,14 +337,24 @@ class ServerNotifier extends StateNotifier<ServerState?> {
return;
}
- controller.add(false);
+ controller.add(null);
controller.close();
closeSession();
}
+ /// Updates the destination directory for the current session.
+ void setSessionDestinationDir(String destinationDirectory) {
+ state = state?.copyWith(
+ receiveState: state?.receiveState?.copyWith(
+ destinationDirectory: destinationDirectory.replaceAll('\\', '/'),
+ ),
+ );
+ }
+
void _cancelBySender() {
final currentStatus = state?.receiveState?.status;
if (currentStatus != null && (currentStatus == SessionStatus.waiting || currentStatus == SessionStatus.sending)) {
+ Routerino.context.popUntil(ReceivePage); // pop just in case if use is in [ReceiveOptionsPage]
state = state?.copyWith(
receiveState: state?.receiveState?.copyWith(
status: SessionStatus.canceledBySender,
diff --git a/lib/provider/network/targeted_discovery_provider.dart b/lib/provider/network/targeted_discovery_provider.dart
index 7242198d..cece707c 100644
--- a/lib/provider/network/targeted_discovery_provider.dart
+++ b/lib/provider/network/targeted_discovery_provider.dart
@@ -6,7 +6,7 @@ import 'package:localsend_app/provider/dio_provider.dart';
import 'package:localsend_app/util/api_route_builder.dart';
final targetedDiscoveryProvider = Provider((ref) {
- final dio = ref.watch(dioProvider(2 * 1000));
+ final dio = ref.watch(dioProvider(DioType.discovery));
return TargetedDiscoveryService(dio);
});
diff --git a/lib/provider/selection/selected_receiving_files_provider.dart b/lib/provider/selection/selected_receiving_files_provider.dart
new file mode 100644
index 00000000..ba793ad5
--- /dev/null
+++ b/lib/provider/selection/selected_receiving_files_provider.dart
@@ -0,0 +1,64 @@
+import 'package:collection/collection.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:localsend_app/model/dto/file_dto.dart';
+import 'package:localsend_app/util/file_path_helper.dart';
+import 'package:uuid/uuid.dart';
+
+const _uuid = Uuid();
+
+/// Manages files to be selected to receive.
+/// Only alive during [ReceivePage], i.e. this provider gets disposed as soon as the actual file transfer begin.
+/// Map: FileId -> FileName
+final selectedReceivingFilesProvider = StateNotifierProvider<SelectedReceivingFilesNotifier, Map<String, String>>((ref) {
+ return SelectedReceivingFilesNotifier();
+});
+
+class SelectedReceivingFilesNotifier extends StateNotifier<Map<String, String>> {
+ SelectedReceivingFilesNotifier() : super({});
+
+ void init(List<FileDto> files) {
+ state = {
+ for (final f in files) f.id: f.fileName, // by default, accept all files and take their original name
+ };
+ }
+
+ void unselect(String fileId) {
+ state = {...state}..remove(fileId);
+ }
+
+ void select(FileDto file) {
+ state = {
+ ...state,
+ file.id: file.fileName,
+ };
+ }
+
+ void rename(String fileId, String fileName) {
+ state = {...state}..update(fileId, (_) => fileName);
+ }
+
+ void applyRandom() {
+ state = {
+ for (final entry in state.entries) entry.key: entry.value.withFileNameKeepExtension(_uuid.v4()),
+ };
+ }
+
+ void applyCounter({
+ required String prefix,
+ required bool padZero,
+ required bool sortFirst,
+ }) {
+ final files = state.entries.toList();
+ if (sortFirst) {
+ files.sort((a, b) => a.value.compareTo(b.value));
+ }
+ final maxKeyStringLength = files.length.toString().length;
+ state = Map.fromEntries(files.mapIndexed((index, element) {
+ String number = (index + 1).toString();
+ if (padZero) {
+ number.padLeft(maxKeyStringLength, '0');
+ }
+ return MapEntry(element.key, element.value.withFileNameKeepExtension('$prefix$number'));
+ }));
+ }
+}
diff --git a/lib/provider/selected_files_provider.dart b/lib/provider/selection/selected_sending_files_provider.dart
similarity index 88%
rename from lib/provider/selected_files_provider.dart
rename to lib/provider/selection/selected_sending_files_provider.dart
index f1e7a6d8..21c92aa9 100644
--- a/lib/provider/selected_files_provider.dart
+++ b/lib/provider/selection/selected_sending_files_provider.dart
@@ -14,12 +14,14 @@ import 'package:wechat_assets_picker/wechat_assets_picker.dart';
const _uuid = Uuid();
-final selectedFilesProvider = StateNotifierProvider<SelectedFilesNotifier, List<CrossFile>>((ref) {
- return SelectedFilesNotifier();
+/// Manages files selected for sending.
+/// Will stay alive even after a session has been completed to send the same files to another device.
+final selectedSendingFilesProvider = StateNotifierProvider<SelectedSendingFilesNotifier, List<CrossFile>>((ref) {
+ return SelectedSendingFilesNotifier();
});
-class SelectedFilesNotifier extends StateNotifier<List<CrossFile>> {
- SelectedFilesNotifier() : super([]);
+class SelectedSendingFilesNotifier extends StateNotifier<List<CrossFile>> {
+ SelectedSendingFilesNotifier() : super([]);
/// Add a simple message
/// Internally, the message will be stored into [CrossFile.bytes] as UTF-8
diff --git a/lib/util/file_path_helper.dart b/lib/util/file_path_helper.dart
index 375f1a3a..b64fb598 100644
--- a/lib/util/file_path_helper.dart
+++ b/lib/util/file_path_helper.dart
@@ -17,6 +17,10 @@ extension FilePathStringExt on String {
return replaceAll('\\', '/').split('/').last;
}
+ String withFileNameKeepExtension(String fileNameWithoutExt) {
+ return '$fileNameWithoutExt.$extension';
+ }
+
String withExtension(String ext) {
if (ext == '') {
return this;
diff --git a/lib/util/file_picker.dart b/lib/util/file_picker.dart
index 41375e12..88ee3757 100644
--- a/lib/util/file_picker.dart
+++ b/lib/util/file_picker.dart
@@ -2,7 +2,7 @@ import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:localsend_app/gen/strings.g.dart';
-import 'package:localsend_app/provider/selected_files_provider.dart';
+import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/widget/dialogs/message_input_dialog.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
@@ -34,7 +34,7 @@ enum FilePickerOption {
case FilePickerOption.file:
final result = await FilePicker.platform.pickFiles(allowMultiple: true);
if (result != null) {
- ref.read(selectedFilesProvider.notifier).addFiles(
+ ref.read(selectedSendingFilesProvider.notifier).addFiles(
files: result.files,
converter: CrossFileConverters.convertPlatformFile,
);
@@ -48,7 +48,7 @@ enum FilePickerOption {
),
);
if (result != null) {
- ref.read(selectedFilesProvider.notifier).addFiles(
+ ref.read(selectedSendingFilesProvider.notifier).addFiles(
files: result,
converter: CrossFileConverters.convertAssetEntity,
);
@@ -57,7 +57,7 @@ enum FilePickerOption {
case FilePickerOption.text:
final result = await showDialog<String>(context: context, builder: (_) => const MessageInputDialog());
if (result != null) {
- ref.read(selectedFilesProvider.notifier).addMessage(result);
+ ref.read(selectedSendingFilesProvider.notifier).addMessage(result);
}
break;
}
diff --git a/lib/widget/dialogs/file_name_input_dialog.dart b/lib/widget/dialogs/file_name_input_dialog.dart
new file mode 100644
index 00000000..6eb461e7
--- /dev/null
+++ b/lib/widget/dialogs/file_name_input_dialog.dart
@@ -0,0 +1,75 @@
+import 'package:flutter/material.dart';
+import 'package:localsend_app/gen/strings.g.dart';
+import 'package:localsend_app/util/file_path_helper.dart';
+import 'package:routerino/routerino.dart';
+
+class FileNameInputDialog extends StatefulWidget {
+ final String originalName;
+ final String initialName;
+
+ const FileNameInputDialog({
+ required this.originalName,
+ required this.initialName,
+ });
+
+ @override
+ State<FileNameInputDialog> createState() => _FileNameInputDialogState();
+}
+
+class _FileNameInputDialogState extends State<FileNameInputDialog> {
+ final _textController = TextEditingController();
+
+ @override
+ void initState() {
+ super.initState();
+ _textController.text = widget.initialName;
+ }
+
+ void _submit() {
+ if (mounted) {
+ String input = _textController.text.trim();
+ if (!input.contains('.') && widget.originalName.contains('.')) {
+ // user forgot extension, we fix it
+ input = input.withExtension(widget.originalName.extension);
+ }
+ context.pop(input);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AlertDialog(
+ title: Text(t.dialogs.fileNameInput.title),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(t.dialogs.fileNameInput.original(original: widget.originalName)),
+ const SizedBox(height: 10),
+ TextFormField(
+ controller: _textController,
+ autofocus: true,
+ onFieldSubmitted: (_) => _submit,
+ ),
+ ],
+ ),
+ actions: [
+ TextButton(
+ style: ElevatedButton.styleFrom(
+ foregroundColor: Theme.of(context).brightness == Brightness.dark ? Theme.of(context).buttonTheme.colorScheme!.onPrimary : null,
+ ),
+ onPressed: () => context.pop(),
+ child: Text(t.general.cancel),
+ ),
+ ElevatedButton(
+ style: ElevatedButton.styleFrom(
+ backgroundColor: Theme.of(context).buttonTheme.colorScheme!.primary,
+ foregroundColor: Theme.of(context).buttonTheme.colorScheme!.onPrimary,
+ ),
+ onPressed: _submit,
+ child: Text(t.general.confirm),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/widget/dialogs/quick_actions_dialog.dart b/lib/widget/dialogs/quick_actions_dialog.dart
new file mode 100644
index 00000000..3398cb30
--- /dev/null
+++ b/lib/widget/dialogs/quick_actions_dialog.dart
@@ -0,0 +1,141 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:localsend_app/gen/strings.g.dart';
+import 'package:localsend_app/provider/selection/selected_receiving_files_provider.dart';
+import 'package:localsend_app/widget/labeled_checkbox.dart';
+import 'package:routerino/routerino.dart';
+import 'package:uuid/uuid.dart';
+
+enum _QuickAction {
+ counter,
+ random;
+
+ String get label {
+ switch (this) {
+ case _QuickAction.counter:
+ return t.dialogs.quickActions.counter;
+ case _QuickAction.random:
+ return t.dialogs.quickActions.random;
+ }
+ }
+}
+
+class QuickActionsDialog extends ConsumerStatefulWidget {
+ const QuickActionsDialog({Key? key}) : super(key: key);
+
+ @override
+ ConsumerState<QuickActionsDialog> createState() => _QuickActionsDialogState();
+}
+
+class _QuickActionsDialogState extends ConsumerState<QuickActionsDialog> {
+ _QuickAction _action = _QuickAction.counter;
+
+ // counter
+ String _prefix = '';
+ bool _padZero = false;
+ bool _sortBeforehand = false;
+
+ // random
+ final _randomUuid = const Uuid().v4();
+
+ @override
+ Widget build(BuildContext context) {
+ return AlertDialog(
+ title: Text(t.dialogs.quickActions.title),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ ToggleButtons(
+ isSelected: [_action == _QuickAction.counter, _action == _QuickAction.random],
+ onPressed: (int index) {
+ setState(() {
+ if (index == 0) {
+ _action = _QuickAction.counter;
+ } else {
+ _action = _QuickAction.random;
+ }
+ });
+ },
+ borderRadius: BorderRadius.circular(10),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ constraints: const BoxConstraints(minWidth: 0, minHeight: 0),
+ children: _QuickAction.values.map((mode) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ child: Text(mode.label),
+ );
+ }).toList(),
+ ),
+ const SizedBox(height: 10),
+ if (_action == _QuickAction.counter) ...[
+ Text(t.dialogs.quickActions.prefix),
+ const SizedBox(height: 5),
+ TextField(
+ autofocus: true,
+ onChanged: (s) {
+ setState(() {
+ _prefix = s;
+ });
+ },
+ ),
+ const SizedBox(height: 10),
+ LabeledCheckbox(
+ label: t.dialogs.quickActions.padZero,
+ value: _padZero,
+ onChanged: (b) {
+ setState(() {
+ _padZero = b == true;
+ });
+ },
+ ),
+ const SizedBox(height: 5),
+ LabeledCheckbox(
+ label: t.dialogs.quickActions.sortBeforeCount,
+ value: _sortBeforehand,
+ onChanged: (b) {
+ setState(() {
+ _sortBeforehand = b == true;
+ });
+ },
+ ),
+ const SizedBox(height: 10),
+ if (_padZero) Text('${t.general.example}: ${_prefix}04.jpg') else Text('${t.general.example}: ${_prefix}4.jpg'),
+ ],
+ if (_action == _QuickAction.random) Text('${t.general.example}: $_randomUuid.jpg'),
+ ],
+ ),
+ actions: [
+ TextButton(
+ style: ElevatedButton.styleFrom(
+ foregroundColor: Theme.of(context).brightness == Brightness.dark ? Theme.of(context).buttonTheme.colorScheme!.onPrimary : null,
+ ),
+ onPressed: () => context.pop(),
+ child: Text(t.general.cancel),
+ ),
+ ElevatedButton(
+ style: ElevatedButton.styleFrom(
+ backgroundColor: Theme.of(context).buttonTheme.colorScheme!.primary,
+ foregroundColor: Theme.of(context).buttonTheme.colorScheme!.onPrimary,
+ ),
+ onPressed: () {
+ switch (_action) {
+ case _QuickAction.counter:
+ ref.read(selectedReceivingFilesProvider.notifier).applyCounter(
+ prefix: _prefix,
+ padZero: _padZero,
+ sortFirst: _sortBeforehand,
+ );
+ break;
+ case _QuickAction.random:
+ ref.read(selectedReceivingFilesProvider.notifier).applyRandom();
+ break;
+ }
+ context.pop();
+ },
+ child: Text(t.general.confirm),
+ ),
+ ],
+ );
+ }
+}
diff --git a/lib/widget/labeled_checkbox.dart b/lib/widget/labeled_checkbox.dart
new file mode 100644
index 00000000..f9ef88b4
--- /dev/null
+++ b/lib/widget/labeled_checkbox.dart
@@ -0,0 +1,26 @@
+import 'package:flutter/material.dart';
+
+class LabeledCheckbox extends StatelessWidget {
+ final String label;
+ final bool value;
+ final ValueChanged<bool?> onChanged;
+ const LabeledCheckbox({
+ required this.label,
+ required this.value,
+ required this.onChanged,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return Row(
+ children: [
+ Checkbox(
+ value: value,
+ onChanged: onChanged,
+ ),
+ const SizedBox(width: 5),
+ Text(label),
+ ],
+ );
+ }
+}