Skip to content

Commit 080487b

Browse files
committed
compose: Support images from keyboard for Android
Fixes: zulip#419 Fixes: zulip#1173 Signed-off-by: Zixuan James Li <[email protected]>
1 parent 2e675c4 commit 080487b

11 files changed

+200
-0
lines changed

assets/l10n/app_en.arb

+8
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,14 @@
458458
"@topicValidationErrorMandatoryButEmpty": {
459459
"description": "Topic validation error when topic is required but was empty."
460460
},
461+
"errorContentNotInsertedTitle": "Content not inserted",
462+
"@errorContentNotInsertedTitle": {
463+
"description": "Title for error dialog when an attempt to insert rich content failed."
464+
},
465+
"errorContentToInsertIsEmpty": "The file to be inserted is empty or cannot be accessed.",
466+
"@errorContentToInsertIsEmpty": {
467+
"description": "Error message when the rich content to be inserted is empty or cannot be accessed."
468+
},
461469
"errorInvalidResponse": "The server sent an invalid response",
462470
"@errorInvalidResponse": {
463471
"description": "Error message when an API call returned an invalid response."

lib/generated/l10n/zulip_localizations.dart

+12
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,18 @@ abstract class ZulipLocalizations {
723723
/// **'Topics are required in this organization.'**
724724
String get topicValidationErrorMandatoryButEmpty;
725725

726+
/// Title for error dialog when an attempt to insert rich content failed.
727+
///
728+
/// In en, this message translates to:
729+
/// **'Content not inserted'**
730+
String get errorContentNotInsertedTitle;
731+
732+
/// Error message when the rich content to be inserted is empty or cannot be accessed.
733+
///
734+
/// In en, this message translates to:
735+
/// **'The file to be inserted is empty or cannot be accessed.'**
736+
String get errorContentToInsertIsEmpty;
737+
726738
/// Error message when an API call returned an invalid response.
727739
///
728740
/// In en, this message translates to:

lib/generated/l10n/zulip_localizations_ar.dart

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ class ZulipLocalizationsAr extends ZulipLocalizations {
357357
@override
358358
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';
359359

360+
@override
361+
String get errorContentNotInsertedTitle => 'Content not inserted';
362+
363+
@override
364+
String get errorContentToInsertIsEmpty => 'The file to be inserted is empty or cannot be accessed.';
365+
360366
@override
361367
String get errorInvalidResponse => 'The server sent an invalid response';
362368

lib/generated/l10n/zulip_localizations_en.dart

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ class ZulipLocalizationsEn extends ZulipLocalizations {
357357
@override
358358
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';
359359

360+
@override
361+
String get errorContentNotInsertedTitle => 'Content not inserted';
362+
363+
@override
364+
String get errorContentToInsertIsEmpty => 'The file to be inserted is empty or cannot be accessed.';
365+
360366
@override
361367
String get errorInvalidResponse => 'The server sent an invalid response';
362368

lib/generated/l10n/zulip_localizations_ja.dart

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ class ZulipLocalizationsJa extends ZulipLocalizations {
357357
@override
358358
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';
359359

360+
@override
361+
String get errorContentNotInsertedTitle => 'Content not inserted';
362+
363+
@override
364+
String get errorContentToInsertIsEmpty => 'The file to be inserted is empty or cannot be accessed.';
365+
360366
@override
361367
String get errorInvalidResponse => 'The server sent an invalid response';
362368

lib/generated/l10n/zulip_localizations_nb.dart

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ class ZulipLocalizationsNb extends ZulipLocalizations {
357357
@override
358358
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';
359359

360+
@override
361+
String get errorContentNotInsertedTitle => 'Content not inserted';
362+
363+
@override
364+
String get errorContentToInsertIsEmpty => 'The file to be inserted is empty or cannot be accessed.';
365+
360366
@override
361367
String get errorInvalidResponse => 'The server sent an invalid response';
362368

lib/generated/l10n/zulip_localizations_pl.dart

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ class ZulipLocalizationsPl extends ZulipLocalizations {
357357
@override
358358
String get topicValidationErrorMandatoryButEmpty => 'Wątki są wymagane przez tę organizację.';
359359

360+
@override
361+
String get errorContentNotInsertedTitle => 'Content not inserted';
362+
363+
@override
364+
String get errorContentToInsertIsEmpty => 'The file to be inserted is empty or cannot be accessed.';
365+
360366
@override
361367
String get errorInvalidResponse => 'Nieprawidłowa odpowiedź serwera';
362368

lib/generated/l10n/zulip_localizations_ru.dart

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ class ZulipLocalizationsRu extends ZulipLocalizations {
357357
@override
358358
String get topicValidationErrorMandatoryButEmpty => 'Темы обязательны в этой организации.';
359359

360+
@override
361+
String get errorContentNotInsertedTitle => 'Content not inserted';
362+
363+
@override
364+
String get errorContentToInsertIsEmpty => 'The file to be inserted is empty or cannot be accessed.';
365+
360366
@override
361367
String get errorInvalidResponse => 'Получен недопустимый ответ сервера';
362368

lib/generated/l10n/zulip_localizations_sk.dart

+6
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ class ZulipLocalizationsSk extends ZulipLocalizations {
357357
@override
358358
String get topicValidationErrorMandatoryButEmpty => 'Topics are required in this organization.';
359359

360+
@override
361+
String get errorContentNotInsertedTitle => 'Content not inserted';
362+
363+
@override
364+
String get errorContentToInsertIsEmpty => 'The file to be inserted is empty or cannot be accessed.';
365+
360366
@override
361367
String get errorInvalidResponse => 'Server poslal nesprávnu odpoveď';
362368

lib/widgets/compose_box.dart

+37
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import 'package:app_settings/app_settings.dart';
44
import 'package:flutter/material.dart';
55
import 'package:flutter/services.dart';
66
import 'package:mime/mime.dart';
7+
import 'package:path/path.dart' as path;
78

89
import '../api/exception.dart';
910
import '../api/model/model.dart';
@@ -366,6 +367,40 @@ class _ContentInputState extends State<_ContentInput> with WidgetsBindingObserve
366367
}
367368
}
368369

370+
void _handleContentInserted(KeyboardInsertedContent content) async {
371+
if (content.data == null || content.data!.isEmpty) {
372+
// As of writing, the engine implementation never leaves `content.data` as
373+
// `null`, but ideally it should be when the data cannot be read for
374+
// errors.
375+
//
376+
// When `content.data` is empty, the data is not literally empty — this
377+
// can also happen when the data can't be read from the input stream
378+
// provided by the Android SDK because of an IO exception.
379+
//
380+
// See Flutter engine implementation that prepares this data:
381+
// https://github.com/flutter/flutter/blob/0ffc4ce00ea7bb912e379adf39354644eab2c17e/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.java#L497-L548
382+
// TODO(upstream): improve the API for this
383+
final zulipLocalizations = ZulipLocalizations.of(context);
384+
showErrorDialog(
385+
context: context,
386+
title: zulipLocalizations.errorContentNotInsertedTitle,
387+
message: zulipLocalizations.errorContentToInsertIsEmpty);
388+
return;
389+
}
390+
391+
final file = _File(
392+
content: Stream.fromIterable([content.data!]),
393+
length: content.data!.length,
394+
filename: path.basename(content.uri),
395+
mimeType: content.mimeType);
396+
397+
await _uploadFiles(
398+
context: context,
399+
contentController: widget.controller.content,
400+
contentFocusNode: widget.controller.contentFocusNode,
401+
files: [file]);
402+
}
403+
369404
static double maxHeight(BuildContext context) {
370405
final clampingTextScaler = MediaQuery.textScalerOf(context)
371406
.clamp(maxScaleFactor: 1.5);
@@ -409,6 +444,8 @@ class _ContentInputState extends State<_ContentInput> with WidgetsBindingObserve
409444
child: TextField(
410445
controller: widget.controller.content,
411446
focusNode: widget.controller.contentFocusNode,
447+
contentInsertionConfiguration: ContentInsertionConfiguration(
448+
onContentInserted: _handleContentInserted),
412449
// Let the content show through the `contentPadding` so that
413450
// our [InsetShadowBox] can fade it smoothly there.
414451
clipBehavior: Clip.none,

test/widgets/compose_box_test.dart

+101
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import 'dart:io';
44

55
import 'package:checks/checks.dart';
66
import 'package:file_picker/file_picker.dart';
7+
import 'package:flutter/services.dart';
78
import 'package:flutter_checks/flutter_checks.dart';
89
import 'package:http/http.dart' as http;
910
import 'package:flutter/material.dart';
@@ -582,6 +583,106 @@ void main() {
582583
// target platform the test is simulating.
583584
// TODO(upstream): unskip after fix to https://github.com/flutter/flutter/issues/161073
584585
skip: Platform.isWindows);
586+
587+
group('attach from keyboard', () {
588+
// This is adapted from:
589+
// https://github.com/flutter/flutter/blob/0ffc4ce00ea7bb912e379adf39354644eab2c17e/packages/flutter/test/widgets/editable_text_test.dart#L724-L740
590+
Future<void> insertContentFromKeyboard(WidgetTester tester, {
591+
required List<int>? data,
592+
required String attachedFileUrl,
593+
required String mimeType,
594+
}) async {
595+
await tester.showKeyboard(contentInputFinder);
596+
// This invokes [EditableText.performAction] on the content [TextField],
597+
// which did not expose an API for testing.
598+
// TODO(upstream): support a better API for testing this
599+
await tester.binding.defaultBinaryMessenger.handlePlatformMessage(
600+
SystemChannels.textInput.name,
601+
SystemChannels.textInput.codec.encodeMethodCall(
602+
MethodCall('TextInputClient.performAction', <dynamic>[
603+
-1,
604+
'TextInputAction.commitContent',
605+
// This fakes data originally provided by the Flutter engine:
606+
// https://github.com/flutter/flutter/blob/0ffc4ce00ea7bb912e379adf39354644eab2c17e/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/InputConnectionAdaptor.java#L497-L548
607+
{
608+
"mimeType": mimeType,
609+
"data": data,
610+
"uri": attachedFileUrl,
611+
},
612+
])),
613+
(ByteData? data) {});
614+
}
615+
616+
testWidgets('success', (tester) async {
617+
const fileContent = [1, 0, 1, 0, 0];
618+
await prepare(tester);
619+
const uploadUrl = '/user_uploads/1/4e/m2A3MSqFnWRLUf9SaPzQ0Up_/test.gif';
620+
connection.prepare(json: UploadFileResult(uri: uploadUrl).toJson());
621+
await insertContentFromKeyboard(tester,
622+
data: fileContent,
623+
attachedFileUrl:
624+
'content://com.zulip.android.zulipboard.provider'
625+
'/root/com.zulip.android.zulipboard/candidate_temp/test.gif',
626+
mimeType: 'image/gif');
627+
628+
await tester.pump();
629+
check(controller!.content.text)
630+
.equals('see image: [Uploading test.gif…]()\n\n');
631+
// (the request is checked more thoroughly in API tests)
632+
check(connection.lastRequest!).isA<http.MultipartRequest>()
633+
..method.equals('POST')
634+
..files.single.which((it) => it
635+
..field.equals('file')
636+
..length.equals(fileContent.length)
637+
..filename.equals('test.gif')
638+
..contentType.asString.equals('image/gif')
639+
..has<Future<List<int>>>((f) => f.finalize().toBytes(), 'contents')
640+
.completes((it) => it.deepEquals(fileContent))
641+
);
642+
checkAppearsLoading(tester, true);
643+
644+
await tester.pump(Duration.zero);
645+
check(controller!.content.text)
646+
.equals('see image: [test.gif]($uploadUrl)\n\n');
647+
checkAppearsLoading(tester, false);
648+
});
649+
650+
testWidgets('data is null', (tester) async {
651+
await prepare(tester);
652+
await insertContentFromKeyboard(tester,
653+
data: null,
654+
attachedFileUrl:
655+
'content://com.zulip.android.zulipboard.provider'
656+
'/root/com.zulip.android.zulipboard/candidate_temp/test.gif',
657+
mimeType: 'image/jpeg');
658+
659+
await tester.pump();
660+
check(controller!.content.text).equals('see image: ');
661+
check(connection.takeRequests()).isEmpty();
662+
checkErrorDialog(tester,
663+
expectedTitle: 'Content not inserted',
664+
expectedMessage: 'The file to be inserted is empty or cannot be accessed.');
665+
checkAppearsLoading(tester, false);
666+
});
667+
668+
testWidgets('data is empty', (tester) async {
669+
await prepare(tester);
670+
await insertContentFromKeyboard(tester,
671+
data: [],
672+
attachedFileUrl:
673+
'content://com.zulip.android.zulipboard.provider'
674+
'/root/com.zulip.android.zulipboard/candidate_temp/test.gif',
675+
mimeType: 'image/jpeg');
676+
677+
await tester.pump();
678+
check(controller!.content.text).equals('see image: ');
679+
check(connection.takeRequests()).isEmpty();
680+
checkErrorDialog(tester,
681+
expectedTitle: 'Content not inserted',
682+
expectedMessage: 'The file to be inserted is empty or cannot be accessed.');
683+
checkAppearsLoading(tester, false);
684+
});
685+
});
585686
});
586687

587688
group('error banner', () {

0 commit comments

Comments
 (0)