Initial commit
This commit is contained in:
75
lib/pages/archive/archive.dart
Normal file
75
lib/pages/archive/archive.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/archive/archive_view.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class Archive extends StatefulWidget {
|
||||
const Archive({super.key});
|
||||
|
||||
@override
|
||||
ArchiveController createState() => ArchiveController();
|
||||
}
|
||||
|
||||
class ArchiveController extends State<Archive> {
|
||||
List<ArchivedRoom> archive = [];
|
||||
|
||||
Future<List<ArchivedRoom>> getArchive(BuildContext context) async {
|
||||
if (archive.isNotEmpty) return archive;
|
||||
return archive = await Matrix.of(context).client.loadArchiveWithTimeline();
|
||||
}
|
||||
|
||||
Future<void> forgetRoomAction(int i) async {
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () async {
|
||||
Logs().v('Forget room ${archive.last.room.getLocalizedDisplayname()}');
|
||||
await archive[i].room.forget();
|
||||
archive.removeAt(i);
|
||||
},
|
||||
);
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> forgetAllAction() async {
|
||||
final archive = this.archive;
|
||||
if (archive.isEmpty) return;
|
||||
if (await showOkCancelAlertDialog(
|
||||
useRootNavigator: false,
|
||||
context: context,
|
||||
title: L10n.of(context).areYouSure,
|
||||
okLabel: L10n.of(context).yes,
|
||||
cancelLabel: L10n.of(context).cancel,
|
||||
message: L10n.of(context).clearArchive,
|
||||
) !=
|
||||
OkCancelResult.ok) {
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
futureWithProgress: (onProgress) async {
|
||||
final count = archive.length;
|
||||
while (archive.isNotEmpty) {
|
||||
onProgress(1 - (archive.length / count));
|
||||
Logs().v(
|
||||
'Forget room ${archive.last.room.getLocalizedDisplayname()}',
|
||||
);
|
||||
await archive.last.room.forget();
|
||||
archive.removeLast();
|
||||
}
|
||||
},
|
||||
);
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ArchiveView(this);
|
||||
}
|
||||
79
lib/pages/archive/archive_view.dart
Normal file
79
lib/pages/archive/archive_view.dart
Normal file
@@ -0,0 +1,79 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/archive/archive.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list_item.dart';
|
||||
import 'package:tatchat/widgets/layouts/max_width_body.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ArchiveView extends StatelessWidget {
|
||||
final ArchiveController controller;
|
||||
|
||||
const ArchiveView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<List<ArchivedRoom>>(
|
||||
future: controller.getArchive(context),
|
||||
builder: (BuildContext context, snapshot) => Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: const Center(child: BackButton()),
|
||||
title: Text(L10n.of(context).archive),
|
||||
actions: [
|
||||
if (snapshot.data?.isNotEmpty ?? false)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: TextButton.icon(
|
||||
onPressed: controller.forgetAllAction,
|
||||
label: Text(L10n.of(context).clearArchive),
|
||||
icon: const Icon(Icons.cleaning_services_outlined),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
withScrolling: false,
|
||||
child: Builder(
|
||||
builder: (BuildContext context) {
|
||||
if (snapshot.hasError) {
|
||||
return Center(
|
||||
child: Text(
|
||||
L10n.of(context).oopsSomethingWentWrong,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator.adaptive(strokeWidth: 2),
|
||||
);
|
||||
} else {
|
||||
if (controller.archive.isEmpty) {
|
||||
return const Center(
|
||||
child: Icon(Icons.archive_outlined, size: 80),
|
||||
);
|
||||
}
|
||||
return ListView.builder(
|
||||
itemCount: controller.archive.length,
|
||||
itemBuilder: (BuildContext context, int i) => ChatListItem(
|
||||
controller.archive[i].room,
|
||||
onForget: () => controller.forgetRoomAction(i),
|
||||
onTap: () => context.go(
|
||||
'/rooms/archive/${controller.archive[i].room.id}',
|
||||
extra: controller.archive[i].timeline,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
96
lib/pages/bootstrap/bootstrap_page.dart
Normal file
96
lib/pages/bootstrap/bootstrap_page.dart
Normal file
@@ -0,0 +1,96 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/bootstrap/view_model/bootstrap_view_model.dart';
|
||||
import 'package:tatchat/pages/bootstrap/widgets/new_passphrase_view.dart';
|
||||
import 'package:tatchat/pages/bootstrap/widgets/restore_bootstrap_view.dart';
|
||||
import 'package:tatchat/pages/bootstrap/widgets/store_recovery_key_view.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/layouts/login_scaffold.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:tatchat/widgets/view_model_builder.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class BootstrapPage extends StatelessWidget {
|
||||
final bool reset;
|
||||
const BootstrapPage({required this.reset, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return ViewModelBuilder(
|
||||
create: () =>
|
||||
BootstrapViewModel(client: Matrix.of(context).client, reset: reset),
|
||||
builder: (context, viewModel, _) {
|
||||
final cryptoIdentityState = viewModel.value.cryptoIdentityState;
|
||||
if (cryptoIdentityState?.connected == true && !reset) {
|
||||
WidgetsBinding.instance.addPostFrameCallback(
|
||||
(_) => viewModel.goToRoomsPageAfterSuccess(context),
|
||||
);
|
||||
}
|
||||
|
||||
final title = cryptoIdentityState == null
|
||||
? L10n.of(context).loadingPleaseWait
|
||||
: cryptoIdentityState.initialized && !viewModel.value.reset
|
||||
? L10n.of(context).restoreCryptoIdentity
|
||||
: viewModel.value.reset
|
||||
? viewModel.value.recoveryKey != null
|
||||
? L10n.of(context).youAreReadyToStart
|
||||
: L10n.of(context).resetCryptoIdentity
|
||||
: L10n.of(context).setUpCryptoIdentity;
|
||||
|
||||
return LoginScaffold(
|
||||
appBar: AppBar(
|
||||
automaticallyImplyLeading: false,
|
||||
leading: viewModel.value.recoveryKey != null
|
||||
? null
|
||||
: CloseButton(
|
||||
onPressed: () async {
|
||||
if (!reset) {
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).skipChatBackup,
|
||||
message: L10n.of(context).skipChatBackupWarning,
|
||||
okLabel: L10n.of(context).skip,
|
||||
isDestructive: true,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!context.mounted) return;
|
||||
}
|
||||
context.go('/rooms');
|
||||
},
|
||||
),
|
||||
title: Text(title),
|
||||
actions: [
|
||||
if (viewModel.value.recoveryKey != null)
|
||||
Padding(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.primary,
|
||||
foregroundColor: theme.colorScheme.onPrimary,
|
||||
padding: EdgeInsets.symmetric(horizontal: 16),
|
||||
),
|
||||
onPressed: () => context.go('/rooms'),
|
||||
child: Text(L10n.of(context).continueText),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
body: cryptoIdentityState == null
|
||||
? Center(child: CircularProgressIndicator.adaptive())
|
||||
: !cryptoIdentityState.initialized || viewModel.value.reset
|
||||
? viewModel.value.recoveryKey == null
|
||||
? NewPassphraseView(viewModel)
|
||||
: StoreRecoveryKeyView(viewModel)
|
||||
: RestoreBootstrapView(viewModel),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
35
lib/pages/bootstrap/view_model/bootstrap_state.dart
Normal file
35
lib/pages/bootstrap/view_model/bootstrap_state.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:matrix/encryption.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class BootstrapViewModelState {
|
||||
String? recoveryKey;
|
||||
bool isLoading = false;
|
||||
Object? unlockWithError;
|
||||
({
|
||||
bool connected,
|
||||
bool crossSigningEnabled,
|
||||
bool initialized,
|
||||
bool keyBackupEnabled,
|
||||
})?
|
||||
cryptoIdentityState;
|
||||
bool reset = false;
|
||||
KeyVerification? keyVerification;
|
||||
List<DeviceKeys>? connectedDevices;
|
||||
bool obscureText = true;
|
||||
bool waitingForSecrets = false;
|
||||
bool noSecretsreceived = false;
|
||||
|
||||
bool newPassphraseEqualsRepeatPassphrase = false;
|
||||
bool newPassphraseLongEnough = false;
|
||||
bool newPassphraseUpperAndLowerCase = false;
|
||||
bool newPassphraseSpecialCharacters = false;
|
||||
bool newPassphraseNumbers = false;
|
||||
bool passphraseOrRecoveryKeyEntered = false;
|
||||
bool recoveryKeyDownloaded = false;
|
||||
bool recoveryKeyStoredInSecureStorage = false;
|
||||
}
|
||||
302
lib/pages/bootstrap/view_model/bootstrap_view_model.dart
Normal file
302
lib/pages/bootstrap/view_model/bootstrap_view_model.dart
Normal file
@@ -0,0 +1,302 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:tatchat/utils/error_reporter.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/encryption.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import 'bootstrap_state.dart';
|
||||
|
||||
class BootstrapViewModel extends ValueNotifier<BootstrapViewModelState> {
|
||||
final Client client;
|
||||
final bool reset;
|
||||
|
||||
final TextEditingController enterPassphraseOrRecovController =
|
||||
TextEditingController();
|
||||
final TextEditingController newPassphraseController = TextEditingController();
|
||||
final TextEditingController repeatPassphraseController =
|
||||
TextEditingController();
|
||||
final ScrollController devicesScrollController = ScrollController();
|
||||
|
||||
BootstrapViewModel({required this.client, required this.reset})
|
||||
: super(BootstrapViewModelState()..reset = reset) {
|
||||
_init();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_cancelKeyVerification();
|
||||
enterPassphraseOrRecovController.dispose();
|
||||
newPassphraseController.dispose();
|
||||
repeatPassphraseController.dispose();
|
||||
devicesScrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _checkCanCreatePassphrase([_]) {
|
||||
final passphrase = newPassphraseController.text;
|
||||
value.newPassphraseEqualsRepeatPassphrase =
|
||||
passphrase.isNotEmpty && passphrase == repeatPassphraseController.text;
|
||||
value.newPassphraseLongEnough = passphrase.length >= 12;
|
||||
value.newPassphraseUpperAndLowerCase =
|
||||
passphrase.contains(RegExp(r'[A-Z]')) &&
|
||||
passphrase.contains(RegExp(r'[a-z]'));
|
||||
value.newPassphraseSpecialCharacters = passphrase.contains(
|
||||
RegExp(r'[!@#$%^&*(),.?":{}|<>]'),
|
||||
);
|
||||
value.newPassphraseNumbers = passphrase.contains(RegExp(r'\d'));
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> retryKeyVerification() async {
|
||||
value.noSecretsreceived = false;
|
||||
value.keyVerification = await client.userDeviceKeys[client.userID!]!
|
||||
.startVerification();
|
||||
value.keyVerification?.onUpdate = _onKeyVerificationUpdate;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _init() async {
|
||||
final state = value.cryptoIdentityState = await client
|
||||
.getCryptoIdentityState();
|
||||
newPassphraseController.addListener(_checkCanCreatePassphrase);
|
||||
repeatPassphraseController.addListener(_checkCanCreatePassphrase);
|
||||
enterPassphraseOrRecovController.addListener(
|
||||
_passphraseOrRecoveryKeyEntered,
|
||||
);
|
||||
if (state.initialized) {
|
||||
if (state.connected) return notifyListeners();
|
||||
|
||||
await client.updateUserDeviceKeys();
|
||||
|
||||
final devices = value.connectedDevices =
|
||||
client.userDeviceKeys[client.userID!]?.deviceKeys.values
|
||||
.where(
|
||||
(device) => device.hasValidSignatureChain(
|
||||
verifiedByTheirMasterKey: true,
|
||||
),
|
||||
)
|
||||
.toList() ??
|
||||
[];
|
||||
if (devices.isNotEmpty) {
|
||||
value.keyVerification = await client.userDeviceKeys[client.userID!]!
|
||||
.startVerification();
|
||||
value.keyVerification?.onUpdate = _onKeyVerificationUpdate;
|
||||
}
|
||||
if (supportsSecureStorage) {
|
||||
try {
|
||||
final keyFromSecureStorage = await FlutterSecureStorage().read(
|
||||
key: _secureStorageKey,
|
||||
);
|
||||
if (keyFromSecureStorage != null) {
|
||||
enterPassphraseOrRecovController.text = keyFromSecureStorage;
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().e('Unable to read key from secure storage', e, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _passphraseOrRecoveryKeyEntered() {
|
||||
final passphraseOrRecoveryKeyEntered =
|
||||
enterPassphraseOrRecovController.text.isNotEmpty;
|
||||
if (value.passphraseOrRecoveryKeyEntered !=
|
||||
passphraseOrRecoveryKeyEntered) {
|
||||
value.passphraseOrRecoveryKeyEntered = passphraseOrRecoveryKeyEntered;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onKeyVerificationUpdate() async {
|
||||
if (value.keyVerification?.state == KeyVerificationState.done) {
|
||||
value.waitingForSecrets = true;
|
||||
value.noSecretsreceived = false;
|
||||
notifyListeners();
|
||||
value.cryptoIdentityState = await client.getCryptoIdentityState();
|
||||
var tries = 0;
|
||||
const max = 10;
|
||||
while (value.cryptoIdentityState?.connected != true) {
|
||||
Logs().d('Waiting for secrets... [$tries/$max]');
|
||||
if (tries >= max) return;
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
value.cryptoIdentityState = await client.getCryptoIdentityState();
|
||||
tries++;
|
||||
}
|
||||
|
||||
if (value.cryptoIdentityState?.connected != true) {
|
||||
value.waitingForSecrets = false;
|
||||
value.noSecretsreceived = true;
|
||||
}
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> setOrSkipPassphrase(
|
||||
String? passphrase,
|
||||
BuildContext context,
|
||||
) async {
|
||||
value.isLoading = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
value.recoveryKey = await client.initCryptoIdentity(
|
||||
passphrase: passphrase,
|
||||
wipeCrossSigning: !reset,
|
||||
wipeKeyBackup: !reset,
|
||||
wipeSecureStorage: !reset,
|
||||
setupOnlineKeyBackup: !reset,
|
||||
setupMasterKey: !reset,
|
||||
setupSelfSigningKey: !reset,
|
||||
setupUserSigningKey: !reset,
|
||||
);
|
||||
} catch (e, s) {
|
||||
if (!context.mounted) return;
|
||||
ErrorReporter(
|
||||
context,
|
||||
'Unable to init crypto identity',
|
||||
).onErrorCallback(e, s);
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
value.isLoading = false;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _cancelKeyVerification() {
|
||||
final keyVerification = value.keyVerification;
|
||||
if (keyVerification != null &&
|
||||
keyVerification.state != KeyVerificationState.done &&
|
||||
keyVerification.state != KeyVerificationState.error) {
|
||||
keyVerification.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
bool get supportsSecureStorage =>
|
||||
PlatformInfos.isMobile || PlatformInfos.isDesktop;
|
||||
|
||||
Future<void> unlock(BuildContext context) async {
|
||||
final key = enterPassphraseOrRecovController.text.trim();
|
||||
if (key.isEmpty) return;
|
||||
|
||||
_cancelKeyVerification();
|
||||
|
||||
value.unlockWithError = null;
|
||||
value.isLoading = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
await client.restoreCryptoIdentity(key);
|
||||
value.isLoading = false;
|
||||
value.cryptoIdentityState = await client.getCryptoIdentityState();
|
||||
notifyListeners();
|
||||
return;
|
||||
} catch (e, s) {
|
||||
if (e is! InvalidPassphraseException) {
|
||||
const errorMessage = 'Unexpected error on unlock passphrase';
|
||||
if (context.mounted) {
|
||||
ErrorReporter(context, errorMessage).onErrorCallback(e, s);
|
||||
} else {
|
||||
Logs().wtf(errorMessage, e, s);
|
||||
}
|
||||
}
|
||||
value.isLoading = false;
|
||||
value.unlockWithError = e;
|
||||
notifyListeners();
|
||||
if (supportsSecureStorage) {
|
||||
await FlutterSecureStorage().delete(key: _secureStorageKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void goToRoomsPageAfterSuccess(BuildContext context) {
|
||||
for (final room in client.rooms) {
|
||||
final lastEvent = room.lastEvent;
|
||||
if (lastEvent == null ||
|
||||
lastEvent.messageType != MessageTypes.BadEncrypted ||
|
||||
lastEvent.content['can_request_session'] != true) {
|
||||
continue;
|
||||
}
|
||||
final sessionId = lastEvent.content.tryGet<String>('session_id');
|
||||
final senderKey = lastEvent.content.tryGet<String>('sender_key');
|
||||
if (sessionId != null && senderKey != null) {
|
||||
client.encryption?.keyManager.maybeAutoRequest(
|
||||
room.id,
|
||||
sessionId,
|
||||
senderKey,
|
||||
);
|
||||
}
|
||||
}
|
||||
context.go('/rooms');
|
||||
}
|
||||
|
||||
void toggleObscureText() {
|
||||
value.obscureText = !value.obscureText;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void startResetAccount() {
|
||||
value.reset = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
String get _secureStorageKey => 'ssss_recovery_key_${client.userID}';
|
||||
|
||||
Future<void> openRecoveryKeyFile(BuildContext context) async {
|
||||
final result = await FilePicker.pickFile(
|
||||
allowedExtensions: ['txt'],
|
||||
type: FileType.custom,
|
||||
);
|
||||
final file = result?.xFile;
|
||||
if (file == null) return;
|
||||
try {
|
||||
final key = await file.readAsString();
|
||||
enterPassphraseOrRecovController.text = key;
|
||||
} catch (e, s) {
|
||||
Logs().d('Unable to read recovery key file', e, s);
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
}
|
||||
}
|
||||
if (context.mounted) await unlock(context);
|
||||
}
|
||||
|
||||
Future<void> toggleRecoveryKeyDownloaded(
|
||||
bool? downloaded,
|
||||
BuildContext context,
|
||||
) async {
|
||||
final path = await FilePicker.saveFile(
|
||||
fileName:
|
||||
'FluffyChat-Recovery-Key-${DateTime.now().toIso8601String()}.txt',
|
||||
bytes: Uint8List.fromList(value.recoveryKey!.codeUnits),
|
||||
);
|
||||
if (path == null) return;
|
||||
value.recoveryKeyDownloaded = downloaded == true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> toggleRecoveryKeyStoredInSecureStorage(bool? stored) async {
|
||||
if (stored == true) {
|
||||
await FlutterSecureStorage().write(
|
||||
key: _secureStorageKey,
|
||||
value: value.recoveryKey,
|
||||
);
|
||||
} else {
|
||||
await FlutterSecureStorage().delete(key: _secureStorageKey);
|
||||
}
|
||||
value.recoveryKeyStoredInSecureStorage = stored == true;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
129
lib/pages/bootstrap/widgets/new_passphrase_view.dart
Normal file
129
lib/pages/bootstrap/widgets/new_passphrase_view.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/bootstrap/view_model/bootstrap_view_model.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class NewPassphraseView extends StatelessWidget {
|
||||
final BootstrapViewModel viewModel;
|
||||
|
||||
const NewPassphraseView(this.viewModel, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final canCreatePassphrase =
|
||||
viewModel.value.newPassphraseEqualsRepeatPassphrase &&
|
||||
viewModel.value.newPassphraseNumbers &&
|
||||
viewModel.value.newPassphraseSpecialCharacters &&
|
||||
viewModel.value.newPassphraseUpperAndLowerCase &&
|
||||
viewModel.value.newPassphraseLongEnough;
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
children: [
|
||||
Text(L10n.of(context).newPassphraseDescription, textAlign: .center),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
obscureText: viewModel.value.obscureText,
|
||||
readOnly: viewModel.value.isLoading,
|
||||
controller: viewModel.newPassphraseController,
|
||||
decoration: InputDecoration(
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
viewModel.value.obscureText
|
||||
? Icons.visibility_off_outlined
|
||||
: Icons.visibility_outlined,
|
||||
),
|
||||
onPressed: viewModel.toggleObscureText,
|
||||
),
|
||||
hintText: L10n.of(context).newPassphrase,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
obscureText: viewModel.value.obscureText,
|
||||
readOnly: viewModel.value.isLoading,
|
||||
controller: viewModel.repeatPassphraseController,
|
||||
decoration: InputDecoration(
|
||||
hintText: L10n.of(context).repeatPassphrase,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: canCreatePassphrase && !viewModel.value.isLoading
|
||||
? () => viewModel.setOrSkipPassphrase(
|
||||
viewModel.newPassphraseController.text,
|
||||
context,
|
||||
)
|
||||
: null,
|
||||
child: viewModel.value.isLoading
|
||||
? CircularProgressIndicator.adaptive()
|
||||
: Text(L10n.of(context).continueText),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextButton(
|
||||
onPressed: viewModel.value.isLoading
|
||||
? null
|
||||
: () => viewModel.setOrSkipPassphrase(null, context),
|
||||
style: TextButton.styleFrom(foregroundColor: theme.colorScheme.error),
|
||||
child: Text(L10n.of(context).skip),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_PassphraseCheckListTile(
|
||||
checked: viewModel.value.newPassphraseEqualsRepeatPassphrase,
|
||||
label: L10n.of(context).passphrasesMatch,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_PassphraseCheckListTile(
|
||||
checked: viewModel.value.newPassphraseLongEnough,
|
||||
label: L10n.of(context).passphraseLengthRequirement,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_PassphraseCheckListTile(
|
||||
checked: viewModel.value.newPassphraseUpperAndLowerCase,
|
||||
label: L10n.of(context).passphraseUpperAndLowerCaseRequirement,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_PassphraseCheckListTile(
|
||||
checked: viewModel.value.newPassphraseSpecialCharacters,
|
||||
label: L10n.of(context).passphraseSpecialCharactersRequirement,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_PassphraseCheckListTile(
|
||||
checked: viewModel.value.newPassphraseNumbers,
|
||||
label: L10n.of(context).passphraseNumberRequirement,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PassphraseCheckListTile extends StatelessWidget {
|
||||
final String label;
|
||||
final bool checked;
|
||||
const _PassphraseCheckListTile({required this.label, required this.checked});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Row(
|
||||
spacing: 8.0,
|
||||
children: [
|
||||
Icon(
|
||||
checked ? Icons.check_circle_outlined : Icons.circle_outlined,
|
||||
color: checked
|
||||
? theme.brightness == Brightness.light
|
||||
? Colors.green.shade800
|
||||
: Colors.green.shade300
|
||||
: theme.colorScheme.error,
|
||||
size: 20,
|
||||
),
|
||||
Text(label, style: TextStyle(fontSize: 12)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
198
lib/pages/bootstrap/widgets/restore_bootstrap_view.dart
Normal file
198
lib/pages/bootstrap/widgets/restore_bootstrap_view.dart
Normal file
@@ -0,0 +1,198 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/bootstrap/view_model/bootstrap_view_model.dart';
|
||||
import 'package:tatchat/pages/key_verification/key_verification_dialog.dart';
|
||||
import 'package:tatchat/utils/date_time_extension.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/device_extension.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/encryption/utils/key_verification.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class RestoreBootstrapView extends StatelessWidget {
|
||||
final BootstrapViewModel viewModel;
|
||||
|
||||
const RestoreBootstrapView(this.viewModel, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final keyVerification = viewModel.value.keyVerification;
|
||||
if (keyVerification != null) {
|
||||
Logs().v('Key verification state:', keyVerification.state);
|
||||
if (keyVerification.state == KeyVerificationState.askSas) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
KeyVerificationDialog(request: keyVerification).show(context);
|
||||
});
|
||||
}
|
||||
}
|
||||
final devices =
|
||||
viewModel.value.connectedDevices
|
||||
?.map(
|
||||
(device) => (
|
||||
title: device.displayname,
|
||||
lastActive: device.lastActive,
|
||||
icon: device.icon,
|
||||
),
|
||||
)
|
||||
.toList() ??
|
||||
[];
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
children: [
|
||||
if (keyVerification != null) ...[
|
||||
ListTile(
|
||||
leading:
|
||||
(keyVerification.state == KeyVerificationState.error ||
|
||||
viewModel.value.noSecretsreceived)
|
||||
? IconButton(
|
||||
onPressed: viewModel.value.isLoading
|
||||
? null
|
||||
: viewModel.retryKeyVerification,
|
||||
tooltip: L10n.of(context).tryAgain,
|
||||
icon: Icon(Icons.refresh_outlined),
|
||||
)
|
||||
: Padding(
|
||||
padding: const EdgeInsets.all(10.0),
|
||||
child: CircularProgressIndicator.adaptive(),
|
||||
),
|
||||
minLeadingWidth: 40,
|
||||
title: Text(
|
||||
viewModel.value.waitingForSecrets
|
||||
? L10n.of(context).waitingForKeys
|
||||
: viewModel.value.noSecretsreceived
|
||||
? L10n.of(context).noKeysTransmitted
|
||||
: L10n.of(context).restoreBootstrapDevicesDescription,
|
||||
|
||||
style: TextStyle(fontSize: 14),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Material(
|
||||
color: theme.colorScheme.surfaceContainer,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: 128),
|
||||
child: Scrollbar(
|
||||
thumbVisibility: true,
|
||||
trackVisibility: true,
|
||||
controller: viewModel.devicesScrollController,
|
||||
child: ListView.builder(
|
||||
controller: viewModel.devicesScrollController,
|
||||
shrinkWrap: true,
|
||||
itemCount: devices.length,
|
||||
itemBuilder: (context, i) => ListTile(
|
||||
leading: CircleAvatar(
|
||||
foregroundColor: theme.colorScheme.onPrimary,
|
||||
backgroundColor: theme.colorScheme.primary,
|
||||
child: Icon(devices[i].icon),
|
||||
),
|
||||
title: Text(
|
||||
devices[i].title,
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
style: TextStyle(fontSize: 14),
|
||||
),
|
||||
subtitle: Text(
|
||||
L10n.of(context).lastActiveAgo(
|
||||
devices[i].lastActive.localizedTime(context),
|
||||
),
|
||||
style: TextStyle(fontSize: 11),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(child: Divider(height: 64)),
|
||||
Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(L10n.of(context).or),
|
||||
),
|
||||
Expanded(child: Divider(height: 64)),
|
||||
],
|
||||
),
|
||||
] else ...[
|
||||
Text(
|
||||
L10n.of(context).restoreBootstrapEmptyDevicesDescription,
|
||||
textAlign: .center,
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
TextField(
|
||||
readOnly: viewModel.value.isLoading,
|
||||
obscureText: viewModel.value.obscureText,
|
||||
controller: viewModel.enterPassphraseOrRecovController,
|
||||
minLines: 1,
|
||||
maxLines: viewModel.value.obscureText ? 1 : 4,
|
||||
onSubmitted: (_) => viewModel.unlock(context),
|
||||
decoration: InputDecoration(
|
||||
hintText: L10n.of(context).passphraseOrKey,
|
||||
prefixIcon: IconButton(
|
||||
icon: Icon(
|
||||
viewModel.value.obscureText
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
),
|
||||
onPressed: viewModel.toggleObscureText,
|
||||
),
|
||||
errorText: viewModel.value.unlockWithError?.toLocalizedString(
|
||||
context,
|
||||
),
|
||||
errorMaxLines: 4,
|
||||
suffixIcon: viewModel.value.isLoading
|
||||
? SizedBox.square(
|
||||
dimension: 32,
|
||||
child: Center(
|
||||
child: CircularProgressIndicator.adaptive(strokeWidth: 2),
|
||||
),
|
||||
)
|
||||
: TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius / 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
onPressed: viewModel.value.passphraseOrRecoveryKeyEntered
|
||||
? () => viewModel.unlock(context)
|
||||
: () => viewModel.openRecoveryKeyFile(context),
|
||||
child: Text(
|
||||
viewModel.value.passphraseOrRecoveryKeyEntered
|
||||
? L10n.of(context).unlock
|
||||
: L10n.of(context).openFile,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).warning,
|
||||
message: L10n.of(context).resetAccountWarning,
|
||||
isDestructive: true,
|
||||
okLabel: L10n.of(context).resetAccount,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!context.mounted) return;
|
||||
viewModel.startResetAccount();
|
||||
},
|
||||
style: TextButton.styleFrom(foregroundColor: theme.colorScheme.error),
|
||||
child: Text(L10n.of(context).resetAccount),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
63
lib/pages/bootstrap/widgets/store_recovery_key_view.dart
Normal file
63
lib/pages/bootstrap/widgets/store_recovery_key_view.dart
Normal file
@@ -0,0 +1,63 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/bootstrap/view_model/bootstrap_view_model.dart';
|
||||
import 'package:tatchat/utils/tatu_share.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class StoreRecoveryKeyView extends StatelessWidget {
|
||||
final BootstrapViewModel viewModel;
|
||||
const StoreRecoveryKeyView(this.viewModel, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
children: [
|
||||
Text(L10n.of(context).storeRecoveryKeyDescription),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
// TODO: Dispose this
|
||||
controller: TextEditingController(text: viewModel.value.recoveryKey),
|
||||
readOnly: true,
|
||||
minLines: 2,
|
||||
maxLines: 4,
|
||||
decoration: InputDecoration(
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(Icons.copy_outlined),
|
||||
onPressed: () =>
|
||||
TatuShare.share(viewModel.value.recoveryKey!, context),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
CheckboxListTile.adaptive(
|
||||
value: viewModel.value.recoveryKeyDownloaded,
|
||||
onChanged: (copied) =>
|
||||
viewModel.toggleRecoveryKeyDownloaded(copied, context),
|
||||
title: Text(L10n.of(context).saveAsFile),
|
||||
),
|
||||
if (viewModel.supportsSecureStorage)
|
||||
CheckboxListTile.adaptive(
|
||||
value: viewModel.value.recoveryKeyStoredInSecureStorage,
|
||||
onChanged: viewModel.toggleRecoveryKeyStoredInSecureStorage,
|
||||
title: Text(_getSecureStorageLocalizedName(context)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _getSecureStorageLocalizedName(BuildContext context) {
|
||||
if (PlatformInfos.isAndroid) {
|
||||
return L10n.of(context).storeInAndroidKeystore;
|
||||
}
|
||||
if (PlatformInfos.isIOS || PlatformInfos.isMacOS) {
|
||||
return L10n.of(context).storeInAppleKeyChain;
|
||||
}
|
||||
return L10n.of(context).storeSecurlyOnThisDevice;
|
||||
}
|
||||
}
|
||||
537
lib/pages/call/call_page.dart
Normal file
537
lib/pages/call/call_page.dart
Normal file
@@ -0,0 +1,537 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/call/call_tile.dart';
|
||||
import 'package:tatchat/pages/call/call_view_model.dart';
|
||||
import 'package:tatchat/pages/call/start_time.dart';
|
||||
import 'package:tatchat/pages/call/utils/get_call_tiles.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:tatchat/widgets/view_model_builder.dart';
|
||||
import 'package:livekit_client/livekit_client.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class CallPage extends StatelessWidget {
|
||||
final String roomId;
|
||||
const CallPage({super.key, required this.roomId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final room = Matrix.of(context).client.getRoomById(roomId)!;
|
||||
final mini = Matrix.of(context).callPosition.value != .fullScreen;
|
||||
final tileSize = FluffyThemes.isColumnMode(context) ? 256.0 : 128.0;
|
||||
return ViewModelBuilder(
|
||||
create: () => CallViewModel(room: room),
|
||||
builder: (context, viewModel, _) {
|
||||
final liveKitRoom = viewModel.value.room;
|
||||
final localVideoTrack = viewModel.value.localVideoTrack;
|
||||
final localParticipant = liveKitRoom?.localParticipant;
|
||||
|
||||
final activeMembers = room.getActiveMatrixRtcMembers().length;
|
||||
final ownUser = room.unsafeGetUserFromMemoryOrFallback(
|
||||
room.client.userID!,
|
||||
);
|
||||
final ownHandRaised = viewModel.participantRaisedHand(ownUser.id);
|
||||
final userIsScreensharing =
|
||||
localParticipant?.isScreenShareEnabled() == true;
|
||||
final iconButtonStyle = IconButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.surfaceBright.withAlpha(230),
|
||||
disabledBackgroundColor: theme.colorScheme.surfaceBright.withAlpha(
|
||||
230,
|
||||
),
|
||||
iconSize: mini ? null : 28,
|
||||
padding: EdgeInsets.all(mini ? 8.0 : 16.0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
side: BorderSide(color: theme.colorScheme.surfaceContainerHighest),
|
||||
),
|
||||
);
|
||||
final iconButtonStyleActive = IconButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.inverseSurface,
|
||||
disabledBackgroundColor: theme.colorScheme.inverseSurface,
|
||||
foregroundColor: theme.colorScheme.onInverseSurface,
|
||||
disabledForegroundColor: theme.colorScheme.onInverseSurface,
|
||||
).merge(iconButtonStyle);
|
||||
|
||||
return MediaQuery.removePadding(
|
||||
context: context,
|
||||
removeBottom: mini,
|
||||
removeTop: mini,
|
||||
child: ScaffoldMessenger(
|
||||
child: Scaffold(
|
||||
extendBodyBehindAppBar: true,
|
||||
appBar: AppBar(
|
||||
automaticallyImplyLeading: false,
|
||||
leading: viewModel.startTime == null
|
||||
? null
|
||||
: StartTime(startTime: viewModel.startTime!),
|
||||
backgroundColor: theme.colorScheme.surface.withAlpha(64),
|
||||
centerTitle: true,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(Icons.fullscreen_outlined),
|
||||
onPressed: () {
|
||||
Matrix.of(context).callPosition.value = mini
|
||||
? .fullScreen
|
||||
: .top;
|
||||
},
|
||||
),
|
||||
if (localVideoTrack == null)
|
||||
PopupMenuButton(
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem(
|
||||
onTap: () => viewModel.selectCamera(context),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
const Icon(Icons.camera_outlined),
|
||||
Text(L10n.of(context).selectCamera),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
onTap: () => viewModel.selectMicrophone(context),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
const Icon(Icons.mic_outlined),
|
||||
Text(L10n.of(context).selectMicrophone),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
onTap: () => viewModel.selectSpeaker(context),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
const Icon(Icons.speaker_phone_outlined),
|
||||
Text(L10n.of(context).selectSpeaker),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
titleSpacing: mini ? 0 : null,
|
||||
title: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Text(
|
||||
room.getLocalizedDisplayname(),
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
style: mini
|
||||
? TextStyle(fontSize: 11, fontWeight: .bold)
|
||||
: null,
|
||||
),
|
||||
if (activeMembers > 0)
|
||||
Text(
|
||||
viewModel.waitForOtherSide
|
||||
? L10n.of(context).waitingForParticipant
|
||||
: L10n.of(
|
||||
context,
|
||||
).countActiveCallMembers(activeMembers),
|
||||
maxLines: 1,
|
||||
style: TextStyle(fontSize: 11),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: liveKitRoom == null
|
||||
? Center(child: CircularProgressIndicator())
|
||||
: localVideoTrack != null
|
||||
? Stack(
|
||||
children: [
|
||||
localVideoTrack.muted
|
||||
? Center(
|
||||
child: Avatar(
|
||||
mxContent: ownUser.avatarUrl,
|
||||
name: ownUser.calcDisplayname(),
|
||||
size: 128,
|
||||
),
|
||||
)
|
||||
: VideoTrackRenderer(localVideoTrack, fit: .cover),
|
||||
|
||||
Align(
|
||||
alignment: .topCenter,
|
||||
child: SafeArea(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: viewModel.value.error == null
|
||||
? theme.colorScheme.errorContainer
|
||||
.withAlpha(230)
|
||||
: theme.colorScheme.error.withAlpha(230),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius,
|
||||
),
|
||||
),
|
||||
margin: EdgeInsets.all(16.0),
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
viewModel.value.error?.toLocalizedString(
|
||||
context,
|
||||
) ??
|
||||
L10n.of(context).videoCallsBetaWarning,
|
||||
textAlign: .center,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
color: viewModel.value.error == null
|
||||
? theme.colorScheme.onErrorContainer
|
||||
: theme.colorScheme.onError,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: SafeArea(
|
||||
top: !mini,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final axis =
|
||||
constraints.maxWidth < constraints.maxHeight
|
||||
? Axis.vertical
|
||||
: Axis.horizontal;
|
||||
|
||||
final tiles = liveKitRoom.getCallTiles(room);
|
||||
|
||||
final focused =
|
||||
(viewModel.value.focusedTrack == null
|
||||
? null
|
||||
: tiles.firstWhereOrNull(
|
||||
(tile) =>
|
||||
tile.id ==
|
||||
viewModel.value.focusedTrack,
|
||||
)) ??
|
||||
tiles.firstWhereOrNull(
|
||||
(tile) => tile.video?.isScreenShare == true,
|
||||
) ??
|
||||
(tiles.length < 3 ? tiles.first : null);
|
||||
|
||||
if (mini) {
|
||||
final miniFocused =
|
||||
focused ??
|
||||
tiles.firstOrNull ??
|
||||
(
|
||||
id: '${ownUser.id}_fallback_none',
|
||||
user: ownUser,
|
||||
video: null,
|
||||
audio: null,
|
||||
connected: false,
|
||||
isSpeaking: false,
|
||||
);
|
||||
return SizedBox.expand(
|
||||
child: CallTile(
|
||||
key: ValueKey(miniFocused.id),
|
||||
user: miniFocused.user,
|
||||
video: miniFocused.video,
|
||||
audio: miniFocused.audio,
|
||||
connected: miniFocused.connected,
|
||||
margin: EdgeInsets.zero,
|
||||
handRaised: viewModel.participantRaisedHand(
|
||||
miniFocused.user.id,
|
||||
),
|
||||
isSpeaking: miniFocused.isSpeaking,
|
||||
onTap: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
tiles.remove(focused);
|
||||
|
||||
return focused == null
|
||||
? Padding(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: 84.0,
|
||||
left: 16.0,
|
||||
right: 16.0,
|
||||
top: 16.0,
|
||||
),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final rows = sqrt(tiles.length).ceil();
|
||||
final columns = (tiles.length / rows)
|
||||
.ceil();
|
||||
|
||||
final width =
|
||||
(constraints.maxWidth / rows) -
|
||||
(rows * 8);
|
||||
final height =
|
||||
(constraints.maxHeight / columns) -
|
||||
(columns * 8);
|
||||
return Center(
|
||||
child: Wrap(
|
||||
spacing: 16.0,
|
||||
runSpacing: 16.0,
|
||||
alignment: .center,
|
||||
runAlignment: .center,
|
||||
crossAxisAlignment: .center,
|
||||
children: tiles
|
||||
.map(
|
||||
(tile) => CallTile(
|
||||
key: ValueKey(tile.id),
|
||||
user: tile.user,
|
||||
video: tile.video,
|
||||
audio: tile.audio,
|
||||
connected: tile.connected,
|
||||
width: width,
|
||||
height: height,
|
||||
isSpeaking: tile.isSpeaking,
|
||||
handRaised: viewModel
|
||||
.participantRaisedHand(
|
||||
tile.user.id,
|
||||
),
|
||||
onTap: () => viewModel
|
||||
.setFocusedTrack(tile.id),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
)
|
||||
: Padding(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: 96.0,
|
||||
left: 16.0,
|
||||
right: 16.0,
|
||||
top: 16.0,
|
||||
),
|
||||
child: Flex(
|
||||
direction: axis,
|
||||
crossAxisAlignment: .stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: CallTile(
|
||||
key: ValueKey(focused.id),
|
||||
user: focused.user,
|
||||
video: focused.video,
|
||||
audio: focused.audio,
|
||||
connected: focused.connected,
|
||||
fit: .contain,
|
||||
isSpeaking: focused.isSpeaking,
|
||||
handRaised: viewModel
|
||||
.participantRaisedHand(
|
||||
focused.user.id,
|
||||
),
|
||||
onTap: () => viewModel
|
||||
.setFocusedTrack(focused.id),
|
||||
),
|
||||
),
|
||||
if (tiles.isNotEmpty) ...[
|
||||
SizedBox(width: 16, height: 16),
|
||||
SizedBox(
|
||||
height: axis == .horizontal
|
||||
? null
|
||||
: tileSize,
|
||||
width: axis == .vertical
|
||||
? null
|
||||
: tileSize,
|
||||
child: ListView.builder(
|
||||
scrollDirection: axis == .horizontal
|
||||
? .vertical
|
||||
: .horizontal,
|
||||
itemCount: tiles.length,
|
||||
itemBuilder: (context, i) =>
|
||||
CallTile(
|
||||
key: ValueKey(tiles[i].id),
|
||||
user: tiles[i].user,
|
||||
video: tiles[i].video,
|
||||
audio: tiles[i].audio,
|
||||
connected: tiles[i].connected,
|
||||
width: tileSize,
|
||||
height: tileSize,
|
||||
isSpeaking:
|
||||
tiles[i].isSpeaking,
|
||||
handRaised: viewModel
|
||||
.participantRaisedHand(
|
||||
tiles[i].user.id,
|
||||
),
|
||||
onTap: () =>
|
||||
viewModel.setFocusedTrack(
|
||||
tiles[i].id,
|
||||
),
|
||||
margin: EdgeInsets.only(
|
||||
right: axis == .vertical
|
||||
? 16
|
||||
: 0,
|
||||
bottom: axis == .horizontal
|
||||
? 16
|
||||
: 0,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
floatingActionButtonLocation: .centerFloat,
|
||||
floatingActionButton: Wrap(
|
||||
alignment: .center,
|
||||
spacing: mini ? 8 : 16,
|
||||
children: [
|
||||
if (localParticipant != null) ...[
|
||||
IconButton(
|
||||
tooltip: L10n.of(context).toggleMicrophone,
|
||||
style: iconButtonStyle,
|
||||
onPressed: () => localParticipant.setMicrophoneEnabled(
|
||||
!localParticipant.isMicrophoneEnabled(),
|
||||
),
|
||||
icon: Icon(
|
||||
localParticipant.isMicrophoneEnabled()
|
||||
? Icons.mic_outlined
|
||||
: Icons.mic_off_outlined,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: L10n.of(context).toggleCamera,
|
||||
style: iconButtonStyle,
|
||||
onPressed: () => localParticipant.setCameraEnabled(
|
||||
!localParticipant.isCameraEnabled(),
|
||||
),
|
||||
icon: Icon(
|
||||
localParticipant.isCameraEnabled()
|
||||
? Icons.videocam_outlined
|
||||
: Icons.videocam_off_outlined,
|
||||
),
|
||||
),
|
||||
if (!PlatformInfos.isMobile) // TODO: Fix on mobile?
|
||||
IconButton(
|
||||
tooltip: userIsScreensharing
|
||||
? L10n.of(context).stopScreensharing
|
||||
: L10n.of(context).startScreensharing,
|
||||
style: userIsScreensharing
|
||||
? iconButtonStyleActive
|
||||
: iconButtonStyle,
|
||||
onPressed: () => localParticipant.setScreenShareEnabled(
|
||||
!userIsScreensharing,
|
||||
),
|
||||
icon: Icon(
|
||||
userIsScreensharing
|
||||
? Icons.stop_screen_share
|
||||
: Icons.screen_share_outlined,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: ownHandRaised
|
||||
? L10n.of(context).stopRaiseHand
|
||||
: L10n.of(context).raiseHand,
|
||||
style: ownHandRaised
|
||||
? iconButtonStyleActive
|
||||
: iconButtonStyle,
|
||||
onPressed: () => showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => ownHandRaised
|
||||
? room.lowerHandInMatrixRtcCall(viewModel.timeline!)
|
||||
: room.raiseHandInMatrixRtcCall(),
|
||||
),
|
||||
icon: Icon(
|
||||
ownHandRaised
|
||||
? Icons.front_hand
|
||||
: Icons.front_hand_outlined,
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: SizedBox(
|
||||
width: 212,
|
||||
child: TextButton.icon(
|
||||
onPressed: viewModel.value.isLoading
|
||||
? null
|
||||
: viewModel.connect,
|
||||
style: ButtonStyle(
|
||||
padding: iconButtonStyleActive.padding,
|
||||
foregroundColor:
|
||||
iconButtonStyleActive.foregroundColor,
|
||||
backgroundColor:
|
||||
iconButtonStyleActive.backgroundColor,
|
||||
),
|
||||
icon: viewModel.value.isLoading
|
||||
? SizedBox.square(
|
||||
dimension: 16,
|
||||
child: CircularProgressIndicator(
|
||||
color: theme.colorScheme.onInverseSurface,
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: Icon(Icons.call_outlined),
|
||||
label: Text(
|
||||
viewModel.value.isLoading
|
||||
? L10n.of(context).loadingPleaseWait
|
||||
: room.hasActiveMatrixRtcCall
|
||||
? L10n.of(context).enterCall
|
||||
: L10n.of(context).startCall,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: L10n.of(context).toggleMicrophone,
|
||||
style: iconButtonStyle,
|
||||
onPressed: viewModel.value.isLoading
|
||||
? null
|
||||
: viewModel.togglePreviewMic,
|
||||
icon: Icon(
|
||||
(viewModel.value.startWithAudio)
|
||||
? Icons.mic_outlined
|
||||
: Icons.mic_off_outlined,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: L10n.of(context).toggleCamera,
|
||||
style: iconButtonStyle,
|
||||
onPressed: viewModel.value.isLoading
|
||||
? null
|
||||
: localVideoTrack != null
|
||||
? viewModel.togglePreviewCamera
|
||||
: null,
|
||||
icon: Icon(
|
||||
!(localVideoTrack?.muted ?? true)
|
||||
? Icons.videocam_outlined
|
||||
: Icons.videocam_off_outlined,
|
||||
),
|
||||
),
|
||||
],
|
||||
IconButton(
|
||||
tooltip: L10n.of(context).hangUp,
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.errorContainer,
|
||||
foregroundColor: theme.colorScheme.onErrorContainer,
|
||||
).merge(iconButtonStyle),
|
||||
|
||||
onPressed: () => viewModel.close(context),
|
||||
icon: Icon(Icons.call_end_outlined),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
140
lib/pages/call/call_tile.dart
Normal file
140
lib/pages/call/call_tile.dart
Normal file
@@ -0,0 +1,140 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:livekit_client/livekit_client.dart' as lk;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class CallTile extends StatelessWidget {
|
||||
final lk.TrackPublication<lk.VideoTrack>? video;
|
||||
final lk.TrackPublication<lk.AudioTrack>? audio;
|
||||
final User user;
|
||||
final EdgeInsets? margin;
|
||||
final VoidCallback? onTap;
|
||||
final lk.VideoViewFit fit;
|
||||
final double width, height;
|
||||
final bool handRaised, connected, isSpeaking;
|
||||
|
||||
const CallTile({
|
||||
super.key,
|
||||
this.video,
|
||||
this.audio,
|
||||
this.width = 256.0,
|
||||
this.height = 256.0,
|
||||
required this.user,
|
||||
required this.onTap,
|
||||
this.handRaised = false,
|
||||
this.fit = lk.VideoViewFit.cover,
|
||||
this.margin,
|
||||
required this.connected,
|
||||
required this.isSpeaking,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final video = this.video?.track;
|
||||
final theme = Theme.of(context);
|
||||
final borderWidth = isSpeaking ? 5.0 : 1.0;
|
||||
|
||||
return SizedBox(
|
||||
width: width,
|
||||
height: height,
|
||||
child: AnimatedContainer(
|
||||
margin: margin,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainer,
|
||||
border: BoxBorder.all(
|
||||
color: isSpeaking
|
||||
? theme.colorScheme.primaryFixedDim
|
||||
: theme.colorScheme.surfaceContainerHighest,
|
||||
width: borderWidth,
|
||||
strokeAlign: BorderSide.strokeAlignOutside,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
child: Stack(
|
||||
children: [
|
||||
video != null && !video.muted
|
||||
? lk.VideoTrackRenderer(video, fit: fit)
|
||||
: Center(
|
||||
child: Avatar(
|
||||
size: 64,
|
||||
mxContent: user.avatarUrl,
|
||||
name: user.calcDisplayname(),
|
||||
),
|
||||
),
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: onTap,
|
||||
),
|
||||
),
|
||||
if (handRaised)
|
||||
Positioned(
|
||||
top: 8,
|
||||
right: 8,
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Icon(
|
||||
Icons.front_hand_outlined,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 8,
|
||||
left: 8,
|
||||
child: Material(
|
||||
elevation: theme.appBarTheme.elevation ?? 4,
|
||||
shadowColor: theme.appBarTheme.shadowColor,
|
||||
borderRadius: BorderRadius.circular(7),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceBright.withAlpha(230),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 4.0,
|
||||
vertical: 2.0,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 4,
|
||||
children: [
|
||||
if (audio != null)
|
||||
Icon(
|
||||
audio?.muted == false ? Icons.mic : Icons.mic_off,
|
||||
size: 12,
|
||||
),
|
||||
if (this.video?.isScreenShare == true)
|
||||
Icon(Icons.screen_share_outlined, size: 12),
|
||||
Text(
|
||||
user.calcDisplayname(),
|
||||
maxLines: 1,
|
||||
style: TextStyle(fontSize: 12),
|
||||
),
|
||||
if (!connected)
|
||||
Icon(Icons.portable_wifi_off_outlined, size: 12),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
621
lib/pages/call/call_view_model.dart
Normal file
621
lib/pages/call/call_view_model.dart
Normal file
@@ -0,0 +1,621 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/call_kit_params.dart';
|
||||
import 'package:tatchat/utils/error_reporter.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/call_keys_event_content.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/utils/position_from_build_context.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart';
|
||||
import 'package:flutter_webrtc/flutter_webrtc.dart' as rtc;
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:livekit_client/livekit_client.dart' as lk;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
|
||||
class CallViewModelState {
|
||||
lk.Room? room;
|
||||
lk.LocalVideoTrack? localVideoTrack;
|
||||
bool startWithAudio = true;
|
||||
bool isLoading = false;
|
||||
Object? error;
|
||||
String? focusedTrack;
|
||||
}
|
||||
|
||||
class CallViewModel extends ValueNotifier<CallViewModelState> {
|
||||
final Room room;
|
||||
Timeline? timeline;
|
||||
final AudioPlayer _audioPlayer = AudioPlayer();
|
||||
DateTime? startTime;
|
||||
StreamSubscription? _onCallEncryptionKeysSub, _onCallMembersChanged;
|
||||
Timer? _resendCallMemberState;
|
||||
bool waitForOtherSide = false;
|
||||
String? callKitId;
|
||||
|
||||
Set<String> _lastSharedParticipants = {};
|
||||
DateTime? _keyCreatedAt;
|
||||
Uint8List? _lastKey;
|
||||
|
||||
lk.BaseKeyProvider? _keyProvider;
|
||||
|
||||
CallViewModel({required this.room}) : super(CallViewModelState()) {
|
||||
_init();
|
||||
}
|
||||
|
||||
void setFocusedTrack(String trackId) {
|
||||
Logs().d('Set focus on', trackId);
|
||||
if (value.focusedTrack == trackId) {
|
||||
value.focusedTrack = null;
|
||||
} else {
|
||||
value.focusedTrack = trackId;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> _onCallEncryptionKeys(CallKeysEvent event) async {
|
||||
final callKeys = event.callKeysContent;
|
||||
final keyProvider = _keyProvider;
|
||||
if (keyProvider == null) {
|
||||
ErrorReporter(
|
||||
null,
|
||||
'Received a new key but the keyProvider is not ready yet!',
|
||||
).onErrorCallback(Exception(), StackTrace.current);
|
||||
return;
|
||||
}
|
||||
|
||||
await keyProvider.setRawKey(
|
||||
base64Decode(callKeys.keys.key),
|
||||
participantId: '${event.sender}:${callKeys.member.claimedDeviceId}',
|
||||
keyIndex: callKeys.keys.index,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _createKeyAndShare() async {
|
||||
final liveKitRoom = value.room;
|
||||
if (liveKitRoom == null) return;
|
||||
|
||||
final ownMemberId = '${room.client.userID}:${room.client.deviceID}';
|
||||
|
||||
final currentParticipants =
|
||||
room
|
||||
.getActiveMatrixRtcMembers()
|
||||
.map((member) => member.membershipId)
|
||||
.whereType<String>()
|
||||
.toSet()
|
||||
..remove(ownMemberId);
|
||||
|
||||
if (setEquals(currentParticipants, _lastSharedParticipants) &&
|
||||
currentParticipants.isNotEmpty) {
|
||||
Logs().d(
|
||||
'Participant list has not changed. No need to share keys again!',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
var index = liveKitRoom.roomOptions.encryption!.keyProvider.getLatestIndex(
|
||||
ownMemberId,
|
||||
);
|
||||
|
||||
final keyCreatedAt = _keyCreatedAt;
|
||||
final canJustForwardToNewUsers =
|
||||
keyCreatedAt != null &&
|
||||
DateTime.now().difference(keyCreatedAt).inSeconds < 15 &&
|
||||
_lastSharedParticipants.difference(currentParticipants).isEmpty;
|
||||
|
||||
late final Uint8List key;
|
||||
if (_lastKey == null || !canJustForwardToNewUsers) {
|
||||
// Key generation
|
||||
final rng = Random.secure();
|
||||
key = Uint8List(16);
|
||||
key.setAll(0, Iterable.generate(key.length, (i) => rng.nextInt(256)));
|
||||
if (_lastKey != null) index = (index + 1) % 256;
|
||||
|
||||
await liveKitRoom.roomOptions.encryption!.keyProvider.setRawKey(
|
||||
key,
|
||||
keyIndex: index,
|
||||
participantId: ownMemberId,
|
||||
);
|
||||
_keyCreatedAt = DateTime.now();
|
||||
_lastKey = key;
|
||||
if (_lastKey != null) {
|
||||
await liveKitRoom.e2eeManager?.setKeyIndex(
|
||||
index,
|
||||
participantIdentity: ownMemberId,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
key = _lastKey!;
|
||||
}
|
||||
|
||||
final forwardParticipants = canJustForwardToNewUsers
|
||||
? currentParticipants.difference(_lastSharedParticipants)
|
||||
: currentParticipants;
|
||||
final deviceKeys = <DeviceKeys>[];
|
||||
for (final membershipId in forwardParticipants) {
|
||||
final membershipParts = membershipId.split(':');
|
||||
final deviceId = membershipParts.removeLast();
|
||||
final userId = membershipParts.join(':');
|
||||
final keys = room.client.userDeviceKeys[userId]?.deviceKeys[deviceId];
|
||||
if (keys == null) {
|
||||
Logs().w('No device keys found for $membershipId');
|
||||
continue;
|
||||
}
|
||||
deviceKeys.add(keys);
|
||||
}
|
||||
|
||||
_lastSharedParticipants = currentParticipants;
|
||||
await room.shareMatrixRtcCallKey(
|
||||
key: key,
|
||||
index: index,
|
||||
memberId: ownMemberId,
|
||||
deviceKeys: deviceKeys,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _init() async {
|
||||
_onCallEncryptionKeysSub = room.client.onCallEncryptionKeys.listen(
|
||||
_onCallEncryptionKeys,
|
||||
);
|
||||
|
||||
await WakelockPlus.enable();
|
||||
await lk.LiveKitClient.initialize();
|
||||
|
||||
// kHKDF matches the key derivation used by element-web's LiveKit JS SDK
|
||||
final keyProviderOptions = rtc.KeyProviderOptions(
|
||||
sharedKey: false,
|
||||
ratchetSalt: Uint8List.fromList('LKFrameEncryptionKey'.codeUnits),
|
||||
ratchetWindowSize: 0,
|
||||
discardFrameWhenCryptorNotReady: true,
|
||||
keyDerivationAlgorithm: rtc.KeyDerivationAlgorithm.kHKDF,
|
||||
keyRingSize: 255,
|
||||
);
|
||||
final nativeKeyProvider = await rtc.frameCryptorFactory
|
||||
.createDefaultKeyProvider(keyProviderOptions);
|
||||
final baseKeyProvider = _keyProvider = lk.BaseKeyProvider(
|
||||
nativeKeyProvider,
|
||||
keyProviderOptions,
|
||||
);
|
||||
|
||||
final liveKitRoom = value.room = lk.Room(
|
||||
roomOptions: lk.RoomOptions(
|
||||
adaptiveStream: true,
|
||||
dynacast: true,
|
||||
defaultAudioCaptureOptions: lk.AudioCaptureOptions(
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
highPassFilter: true,
|
||||
),
|
||||
defaultScreenShareCaptureOptions: lk.ScreenShareCaptureOptions(
|
||||
useiOSBroadcastExtension: PlatformInfos.isIOS,
|
||||
),
|
||||
defaultAudioOutputOptions: lk.AudioOutputOptions(
|
||||
speakerOn: PlatformInfos.isMobile,
|
||||
),
|
||||
encryption: lk.E2EEOptions(keyProvider: baseKeyProvider),
|
||||
),
|
||||
);
|
||||
|
||||
liveKitRoom.events.on<lk.ParticipantConnectedEvent>((event) async {
|
||||
if (event.participant.identity ==
|
||||
liveKitRoom.localParticipant?.identity) {
|
||||
return;
|
||||
}
|
||||
if (waitForOtherSide) {
|
||||
waitForOtherSide = false;
|
||||
await _audioPlayer.stop();
|
||||
final callKitId = this.callKitId;
|
||||
if (callKitId != null) {
|
||||
await FlutterCallkitIncoming.setCallConnected(callKitId);
|
||||
}
|
||||
}
|
||||
_playJoinSound();
|
||||
});
|
||||
|
||||
liveKitRoom.events.on<lk.ParticipantDisconnectedEvent>(_playLeaveSound);
|
||||
|
||||
liveKitRoom.events.on<lk.TrackE2EEStateEvent>((event) {
|
||||
if (event.state == .kOk || event.state == .kNew) {
|
||||
Logs().i(
|
||||
'E2EE event from ${event.participant} (${event.publication})',
|
||||
event.state,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (event.state == .kMissingKey) {
|
||||
Logs().d('Waiting for call key...', event);
|
||||
return;
|
||||
}
|
||||
Logs().e('LiveKit E2EE Error', event);
|
||||
});
|
||||
|
||||
liveKitRoom.addListener(notifyListeners);
|
||||
|
||||
if (room.isDirectChat && room.hasActiveMatrixRtcCall) {
|
||||
await connect();
|
||||
} else {
|
||||
value.localVideoTrack = await lk.LocalVideoTrack.createCameraTrack();
|
||||
if (room.getActiveMatrixRtcMembers().firstOrNull?.callIntent == .voice) {
|
||||
value.localVideoTrack?.mute();
|
||||
}
|
||||
value.localVideoTrack?.addListener(notifyListeners);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> togglePreviewCamera() async {
|
||||
final track = value.localVideoTrack;
|
||||
if (track == null) return;
|
||||
if (!track.muted) {
|
||||
await track.mute();
|
||||
return;
|
||||
}
|
||||
track.removeListener(notifyListeners);
|
||||
await track.stop();
|
||||
value.localVideoTrack = await lk.LocalVideoTrack.createCameraTrack();
|
||||
value.localVideoTrack?.addListener(notifyListeners);
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void togglePreviewMic() {
|
||||
value.startWithAudio = !value.startWithAudio;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
bool participantRaisedHand(String matrixId) {
|
||||
final timeline = this.timeline;
|
||||
if (timeline == null) return false;
|
||||
return room.participantRaisedHandInMatrixRtcCall(matrixId, timeline);
|
||||
}
|
||||
|
||||
Future<void> _onNewTimelineEvent(int i) async {
|
||||
final event = timeline?.events[i];
|
||||
if (event == null) return;
|
||||
switch (event.type) {
|
||||
case 'io.element.call.reaction':
|
||||
Logs().d(
|
||||
'Call reactions are not yet handled',
|
||||
event.content.tryGet<String>('emoji'),
|
||||
);
|
||||
// TODO: handle reaction
|
||||
break;
|
||||
case EventTypes.Reaction:
|
||||
final reactedEvent = await timeline!.getEventById(
|
||||
event.relationshipEventId!,
|
||||
);
|
||||
if (reactedEvent != null &&
|
||||
reactedEvent.type == MatrixRtcCallMember.eventType &&
|
||||
event.senderId == reactedEvent.senderId &&
|
||||
event.content
|
||||
.tryGetMap<String, Object?>('m.relates_to')
|
||||
?.tryGet<String>('key') ==
|
||||
'🖐️') {
|
||||
Logs().d('User raised hand!');
|
||||
_playRaiseHandSound();
|
||||
notifyListeners();
|
||||
}
|
||||
break;
|
||||
case EventTypes.Redaction:
|
||||
notifyListeners();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> connect() async {
|
||||
try {
|
||||
value.isLoading = true;
|
||||
notifyListeners();
|
||||
final playWaitingSound =
|
||||
!room.hasActiveMatrixRtcCall && room.isDirectChat;
|
||||
|
||||
final intent =
|
||||
room.getActiveMatrixRtcMembers().firstOrNull?.callIntent ??
|
||||
(value.localVideoTrack?.muted == false ? .video : .voice);
|
||||
if (PlatformInfos.isMobile) {
|
||||
await lk.AudioManager.instance.setSpeakerOutputPreferred(
|
||||
intent == .video,
|
||||
);
|
||||
}
|
||||
|
||||
timeline = await room.getTimeline(onInsert: _onNewTimelineEvent);
|
||||
final credentials = await room.joinMatrixRtcCall(intent: intent);
|
||||
_onCallMembersChanged = room.client.onSync.stream
|
||||
.where(
|
||||
(syncUpdate) =>
|
||||
syncUpdate.rooms?.join?[room.id]?.timeline?.events?.any(
|
||||
(event) => event.type == MatrixRtcCallMember.eventType,
|
||||
) ??
|
||||
false,
|
||||
)
|
||||
.listen((_) {
|
||||
notifyListeners();
|
||||
_createKeyAndShare();
|
||||
});
|
||||
await _createKeyAndShare();
|
||||
|
||||
final startWithVideo =
|
||||
!(value.localVideoTrack?.muted ?? intent == .voice);
|
||||
final startWithAudio = value.startWithAudio;
|
||||
await value.localVideoTrack?.stop();
|
||||
await value.localVideoTrack?.dispose();
|
||||
value.localVideoTrack = null;
|
||||
await value.room!.connect(
|
||||
credentials.url,
|
||||
credentials.jwt,
|
||||
fastConnectOptions: lk.FastConnectOptions(
|
||||
microphone: lk.TrackOption(
|
||||
track: startWithAudio ? await lk.LocalAudioTrack.create() : null,
|
||||
),
|
||||
camera: lk.TrackOption(
|
||||
track: startWithVideo
|
||||
? await lk.LocalVideoTrack.createCameraTrack()
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
_resendCallMemberState?.cancel();
|
||||
_resendCallMemberState = Timer.periodic(const Duration(hours: 1), (_) {
|
||||
final ownMembership = room.ownMatrixRtcMembership;
|
||||
if (ownMembership == null) {
|
||||
_resendCallMemberState?.cancel();
|
||||
return;
|
||||
}
|
||||
room.setMatrixRtcMembershipState(
|
||||
ownMembership.fociPreferred,
|
||||
intent: intent,
|
||||
);
|
||||
});
|
||||
startTime = DateTime.now();
|
||||
|
||||
if (PlatformInfos.isMobile) {
|
||||
final activeCalls = await FlutterCallkitIncoming.activeCalls();
|
||||
callKitId = activeCalls
|
||||
.firstWhereOrNull(
|
||||
(call) =>
|
||||
call.extra?['roomId'] == room.id &&
|
||||
call.extra?['clientName'] == room.client.clientName,
|
||||
)
|
||||
?.id;
|
||||
if (callKitId == null) {
|
||||
final params = await buildFluffyChatCallKitParams(
|
||||
room,
|
||||
intent: intent,
|
||||
);
|
||||
await FlutterCallkitIncoming.startCall(params);
|
||||
callKitId = params.id;
|
||||
}
|
||||
}
|
||||
if (playWaitingSound) {
|
||||
waitForOtherSide = true;
|
||||
_playWaitingSound();
|
||||
} else {
|
||||
final callKitId = this.callKitId;
|
||||
if (callKitId != null) {
|
||||
await FlutterCallkitIncoming.setCallConnected(callKitId);
|
||||
}
|
||||
_playJoinSound();
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
} catch (e, s) {
|
||||
Logs().e('Error while connecting', e, s);
|
||||
value.error = e;
|
||||
ErrorReporter(null, 'Unable to connect').onErrorCallback(e, s);
|
||||
} finally {
|
||||
value.isLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> close(BuildContext context) async {
|
||||
_playLeaveSound();
|
||||
final liveKitRoom = value.room;
|
||||
if (liveKitRoom != null) {
|
||||
liveKitRoom.removeListener(notifyListeners);
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () async {
|
||||
if (liveKitRoom.connectionState != lk.ConnectionState.disconnected) {
|
||||
await liveKitRoom.disconnect();
|
||||
}
|
||||
await liveKitRoom.dispose();
|
||||
value.room = null;
|
||||
if (room.ownMatrixRtcMembership != null) {
|
||||
await room.leaveMatrixRtcCall();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
if (context.mounted) {
|
||||
Matrix.of(context).activeCallRoomId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_onCallEncryptionKeysSub?.cancel();
|
||||
_onCallMembersChanged?.cancel();
|
||||
_resendCallMemberState?.cancel();
|
||||
timeline?.cancelSubscriptions();
|
||||
value.localVideoTrack?.dispose();
|
||||
final callKitId = this.callKitId;
|
||||
if (callKitId != null) {
|
||||
FlutterCallkitIncoming.endCall(callKitId);
|
||||
}
|
||||
final liveKitRoom = value.room;
|
||||
if (liveKitRoom != null) {
|
||||
liveKitRoom.removeListener(notifyListeners);
|
||||
if (liveKitRoom.connectionState != lk.ConnectionState.disconnected) {
|
||||
liveKitRoom.disconnect();
|
||||
}
|
||||
liveKitRoom.dispose();
|
||||
room.leaveMatrixRtcCall();
|
||||
}
|
||||
_audioPlayer.dispose();
|
||||
WakelockPlus.disable();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _playSoundIndex(
|
||||
AudioSource audioSource, {
|
||||
LoopMode loopMode = .off,
|
||||
}) async {
|
||||
if (_audioPlayer.playing) await _audioPlayer.stop();
|
||||
await _audioPlayer.setAudioSource(audioSource);
|
||||
if (_audioPlayer.loopMode != loopMode) {
|
||||
await _audioPlayer.setLoopMode(loopMode);
|
||||
}
|
||||
try {
|
||||
await _audioPlayer.play();
|
||||
} catch (e) {
|
||||
Logs().w('Unable to start audio player. Try again...', e);
|
||||
await Future.delayed(const Duration(milliseconds: 300));
|
||||
await _audioPlayer.play();
|
||||
}
|
||||
}
|
||||
|
||||
final _joinSource = AudioSource.asset('assets/sounds/call_join.mp3');
|
||||
final _leaveSource = AudioSource.asset('assets/sounds/call_leave.mp3');
|
||||
final _raiseHandSource = AudioSource.asset(
|
||||
'assets/sounds/call_attention.mp3',
|
||||
);
|
||||
final _waitSource = AudioSource.asset('assets/sounds/call_wait.mp3');
|
||||
|
||||
Future<void> _playJoinSound() => _playSoundIndex(_joinSource);
|
||||
|
||||
Future<void> _playLeaveSound([_]) => _playSoundIndex(_leaveSource);
|
||||
|
||||
Future<void> _playRaiseHandSound() => _playSoundIndex(_raiseHandSource);
|
||||
|
||||
Future<void> _playWaitingSound() =>
|
||||
_playSoundIndex(_waitSource, loopMode: .all);
|
||||
|
||||
Future<lk.MediaDevice?> _selectMediaDevice(
|
||||
BuildContext context,
|
||||
List<lk.MediaDevice> devices,
|
||||
String? activeDeviceId,
|
||||
) async {
|
||||
if (!context.mounted) return null;
|
||||
return await showMenu<lk.MediaDevice>(
|
||||
context: context,
|
||||
position: context.position,
|
||||
items: devices.isEmpty
|
||||
? [
|
||||
PopupMenuItem(
|
||||
enabled: false,
|
||||
child: Text(L10n.of(context).noDevicesFound),
|
||||
),
|
||||
]
|
||||
: devices
|
||||
.map(
|
||||
(device) => PopupMenuItem(
|
||||
value: device,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
Icon(
|
||||
device.deviceId == activeDeviceId
|
||||
? Icons.check_circle_outlined
|
||||
: Icons.circle_outlined,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
device.label,
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> selectCamera(BuildContext context) async {
|
||||
final devices = await lk.Hardware.instance.videoInputs();
|
||||
if (!context.mounted) return;
|
||||
final source = await _selectMediaDevice(
|
||||
context,
|
||||
devices,
|
||||
value.room?.selectedVideoInputDeviceId,
|
||||
);
|
||||
if (source == null) return;
|
||||
await value.room?.setVideoInputDevice(source);
|
||||
}
|
||||
|
||||
Future<void> selectMicrophone(BuildContext context) async {
|
||||
final devices = await lk.Hardware.instance.audioInputs();
|
||||
if (!context.mounted) return;
|
||||
final source = await _selectMediaDevice(
|
||||
context,
|
||||
devices,
|
||||
value.room?.selectedAudioInputDeviceId,
|
||||
);
|
||||
if (source == null) return;
|
||||
await value.room?.setAudioInputDevice(source);
|
||||
}
|
||||
|
||||
Future<void> selectSpeaker(BuildContext context) async {
|
||||
final devices = await lk.Hardware.instance.audioOutputs();
|
||||
if (!context.mounted) return;
|
||||
if (devices.isEmpty && PlatformInfos.isMobile) {
|
||||
final preferSpeaker = lk.AudioManager.instance.isSpeakerOutputPreferred;
|
||||
final toggle = await showMenu<bool>(
|
||||
context: context,
|
||||
position: context.position,
|
||||
items: [
|
||||
PopupMenuItem(
|
||||
value: true,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
Icon(
|
||||
preferSpeaker
|
||||
? Icons.check_circle_outlined
|
||||
: Icons.circle_outlined,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
L10n.of(context).preferSpeaker,
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
if (toggle == null) return;
|
||||
await lk.AudioManager.instance.setSpeakerOutputPreferred(!preferSpeaker);
|
||||
return;
|
||||
}
|
||||
final source = await _selectMediaDevice(
|
||||
context,
|
||||
devices,
|
||||
value.room?.selectedAudioOutputDeviceId,
|
||||
);
|
||||
if (source == null) return;
|
||||
await value.room?.setAudioOutputDevice(source);
|
||||
}
|
||||
}
|
||||
43
lib/pages/call/start_time.dart
Normal file
43
lib/pages/call/start_time.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
class StartTime extends StatefulWidget {
|
||||
final DateTime startTime;
|
||||
const StartTime({required this.startTime, super.key});
|
||||
|
||||
@override
|
||||
State<StartTime> createState() => _StartTimeState();
|
||||
}
|
||||
|
||||
class _StartTimeState extends State<StartTime> {
|
||||
late final Timer _timer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (_) => setState(() {}));
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final duration = DateTime.now().difference(widget.startTime);
|
||||
return Center(
|
||||
child: Text(
|
||||
'${duration.inMinutes.toString().padLeft(2, '0')}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}',
|
||||
style: TextStyle(fontSize: 11),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
109
lib/pages/call/utils/get_call_tiles.dart
Normal file
109
lib/pages/call/utils/get_call_tiles.dart
Normal file
@@ -0,0 +1,109 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:livekit_client/livekit_client.dart' as lk;
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
typedef TileData = ({
|
||||
String id,
|
||||
lk.TrackPublication<lk.VideoTrack>? video,
|
||||
lk.TrackPublication<lk.AudioTrack>? audio,
|
||||
User user,
|
||||
bool connected,
|
||||
bool isSpeaking,
|
||||
});
|
||||
|
||||
extension GetCallTiles on lk.Room {
|
||||
/// Calculates all call tiles to be rendered for this call in this matrix
|
||||
/// room. For users without any camera track it adds a CallTile with a
|
||||
/// null video track at least.
|
||||
List<TileData> getCallTiles(Room room) {
|
||||
final tiles = <TileData>[];
|
||||
|
||||
for (final member in room.getActiveMatrixRtcMembers()) {
|
||||
final participantId = '${member.senderId}:${member.deviceId}';
|
||||
|
||||
// The local user is handled below:
|
||||
if (localParticipant?.identity == participantId ||
|
||||
(member.senderId == room.client.userID &&
|
||||
member.deviceId == room.client.deviceID)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final participant =
|
||||
remoteParticipants[participantId] ??
|
||||
remoteParticipants[member.membershipId];
|
||||
final matrixId = member.senderId ?? participant?.matrixId;
|
||||
if (matrixId == null) {
|
||||
Logs().wtf('No matrix ID found for this member!');
|
||||
continue;
|
||||
}
|
||||
final user = room.unsafeGetUserFromMemoryOrFallback(matrixId);
|
||||
final audio = participant?.audioTrackPublications.firstOrNull;
|
||||
if (participant == null ||
|
||||
!participant.videoTrackPublications.any(
|
||||
(pub) => !pub.isScreenShare,
|
||||
)) {
|
||||
tiles.add((
|
||||
id: '${participantId}_none',
|
||||
user: user,
|
||||
video: null,
|
||||
audio: audio,
|
||||
connected: participant != null,
|
||||
isSpeaking: participant?.isSpeaking == true,
|
||||
));
|
||||
}
|
||||
for (final pub
|
||||
in participant?.videoTrackPublications ??
|
||||
<lk.RemoteTrackPublication<lk.RemoteVideoTrack>>[]) {
|
||||
tiles.add((
|
||||
id: '${participantId}_${pub.name}',
|
||||
user: user,
|
||||
video: pub,
|
||||
audio: pub.isScreenShare ? null : audio,
|
||||
connected: participant != null,
|
||||
isSpeaking: participant?.isSpeaking == true && !pub.isScreenShare,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Handle the local participant here:
|
||||
final ownUser = room.unsafeGetUserFromMemoryOrFallback(room.client.userID!);
|
||||
for (final pub
|
||||
in localParticipant?.videoTrackPublications ??
|
||||
<lk.LocalTrackPublication<lk.LocalVideoTrack>>[]) {
|
||||
tiles.add((
|
||||
id: '${localParticipant?.identity ?? ownUser.id}_${pub.name}',
|
||||
user: ownUser,
|
||||
video: pub,
|
||||
audio: localParticipant?.audioTrackPublications.firstOrNull,
|
||||
connected: localParticipant != null,
|
||||
isSpeaking: localParticipant?.isSpeaking == true && !pub.isScreenShare,
|
||||
));
|
||||
}
|
||||
|
||||
if (localParticipant?.videoTrackPublications.any(
|
||||
(pub) => !pub.isScreenShare,
|
||||
) !=
|
||||
true) {
|
||||
tiles.add((
|
||||
id: '${localParticipant?.identity ?? ownUser.id}_none',
|
||||
user: ownUser,
|
||||
video: null,
|
||||
audio: localParticipant?.audioTrackPublications.firstOrNull,
|
||||
connected: localParticipant != null,
|
||||
isSpeaking: localParticipant?.isSpeaking == true,
|
||||
));
|
||||
}
|
||||
|
||||
return tiles;
|
||||
}
|
||||
}
|
||||
|
||||
extension on lk.RemoteParticipant {
|
||||
String get matrixId => (identity.split(':')..removeLast()).join(':');
|
||||
}
|
||||
1665
lib/pages/chat/chat.dart
Normal file
1665
lib/pages/chat/chat.dart
Normal file
File diff suppressed because it is too large
Load Diff
68
lib/pages/chat/chat_app_bar_list_tile.dart
Normal file
68
lib/pages/chat/chat_app_bar_list_tile.dart
Normal file
@@ -0,0 +1,68 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class ChatAppBarListTile extends StatelessWidget {
|
||||
final Widget? leading;
|
||||
final String title;
|
||||
final Widget? trailing;
|
||||
final void Function()? onTap;
|
||||
|
||||
static const double fixedHeight = 40.0;
|
||||
|
||||
const ChatAppBarListTile({
|
||||
super.key,
|
||||
this.leading,
|
||||
required this.title,
|
||||
this.trailing,
|
||||
this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final leading = this.leading;
|
||||
final trailing = this.trailing;
|
||||
return SizedBox(
|
||||
height: fixedHeight,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
child: Row(
|
||||
children: [
|
||||
?leading,
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4.0),
|
||||
child: Linkify(
|
||||
text: title,
|
||||
textScaleFactor: MediaQuery.textScalerOf(context).scale(1),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
fontSize: 14,
|
||||
),
|
||||
linkStyle: TextStyle(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
fontSize: 14,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
onOpen: (url) => UrlLauncher(context, url.url).launchUrl(),
|
||||
),
|
||||
),
|
||||
),
|
||||
?trailing,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
179
lib/pages/chat/chat_app_bar_title.dart
Normal file
179
lib/pages/chat/chat_app_bar_title.dart
Normal file
@@ -0,0 +1,179 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/chat.dart';
|
||||
import 'package:tatchat/utils/date_time_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/utils/sync_status_localization.dart';
|
||||
import 'package:tatchat/utils/verified_room_extension.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/presence_builder.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatAppBarTitle extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
const ChatAppBarTitle(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final room = controller.room;
|
||||
if (controller.selectedEvents.isNotEmpty) {
|
||||
return Text(
|
||||
controller.selectedEvents.length.toString(),
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onTertiaryContainer,
|
||||
),
|
||||
);
|
||||
}
|
||||
return InkWell(
|
||||
hoverColor: Colors.transparent,
|
||||
splashColor: Colors.transparent,
|
||||
highlightColor: Colors.transparent,
|
||||
onTap: controller.isArchived
|
||||
? null
|
||||
: () => FluffyThemes.isThreeColumnMode(context)
|
||||
? controller.toggleDisplayChatDetailsColumn()
|
||||
: context.go('/rooms/${room.id}/details'),
|
||||
child: Row(
|
||||
children: [
|
||||
Hero(
|
||||
tag: 'content_banner',
|
||||
child: Avatar(
|
||||
mxContent: room.avatar,
|
||||
name: room.getLocalizedDisplayname(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
),
|
||||
size: 32,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
crossAxisAlignment: .start,
|
||||
children: [
|
||||
Row(
|
||||
spacing: 4,
|
||||
children: [
|
||||
if (room.allUsersVerified)
|
||||
Icon(
|
||||
Icons.verified,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
size: 16,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
room.getLocalizedDisplayname(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
StreamBuilder(
|
||||
stream: room.client.onSyncStatus.stream,
|
||||
builder: (context, snapshot) {
|
||||
final status =
|
||||
room.client.onSyncStatus.value ??
|
||||
const SyncStatusUpdate(SyncStatus.waitingForResponse);
|
||||
final hide =
|
||||
FluffyThemes.isColumnMode(context) ||
|
||||
(room.client.onSync.value != null &&
|
||||
status.status != SyncStatus.error &&
|
||||
room.client.prevBatch != null);
|
||||
final style = TextStyle(fontSize: 11);
|
||||
return AnimatedSize(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
child: hide
|
||||
? room.isDirectChat
|
||||
? PresenceBuilder(
|
||||
userId: room.directChatMatrixID,
|
||||
builder: (context, presence) {
|
||||
final statusMessage = presence?.statusMsg
|
||||
?.trim();
|
||||
|
||||
final lastActiveTimestamp =
|
||||
presence?.lastActiveTimestamp;
|
||||
|
||||
final texts = [
|
||||
if (presence?.currentlyActive == true)
|
||||
L10n.of(context).currentlyActive
|
||||
else if (lastActiveTimestamp != null)
|
||||
L10n.of(context).lastActiveAgo(
|
||||
lastActiveTimestamp
|
||||
.localizedTimeShort(context),
|
||||
),
|
||||
?statusMessage,
|
||||
];
|
||||
final text = texts.join(' ◦ ');
|
||||
if (text.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Text(text, style: style);
|
||||
},
|
||||
)
|
||||
: Row(
|
||||
children: [
|
||||
Text(
|
||||
L10n.of(context).countParticipants(
|
||||
(room.summary.mJoinedMemberCount ??
|
||||
1) +
|
||||
(room
|
||||
.summary
|
||||
.mInvitedMemberCount ??
|
||||
0),
|
||||
),
|
||||
maxLines: 1,
|
||||
style: style,
|
||||
),
|
||||
if (room.topic.isNotEmpty) ...[
|
||||
Text(' ◦ ', style: style),
|
||||
Expanded(
|
||||
child: Text(
|
||||
room.topic,
|
||||
style: style,
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
)
|
||||
: Row(
|
||||
children: [
|
||||
SizedBox.square(
|
||||
dimension: 10,
|
||||
child: CircularProgressIndicator.adaptive(
|
||||
strokeWidth: 1,
|
||||
value: status.progress,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: Text(
|
||||
status.calcLocalizedString(context),
|
||||
style: TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
125
lib/pages/chat/chat_emoji_picker.dart
Normal file
125
lib/pages/chat/chat_emoji_picker.dart
Normal file
@@ -0,0 +1,125 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/sticker_picker_dialog.dart';
|
||||
import 'package:tatchat/pages/chat/trust_user_key_dialog.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import 'chat.dart';
|
||||
|
||||
class ChatEmojiPicker extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
const ChatEmojiPicker(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AnimatedContainer(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
decoration: const BoxDecoration(),
|
||||
height: controller.showEmojiPicker
|
||||
? MediaQuery.sizeOf(context).height / 2
|
||||
: 0,
|
||||
child: controller.showEmojiPicker
|
||||
? DefaultTabController(
|
||||
length: 2,
|
||||
child: Column(
|
||||
children: [
|
||||
TabBar(
|
||||
tabs: [
|
||||
Tab(text: L10n.of(context).emojis),
|
||||
Tab(text: L10n.of(context).stickers),
|
||||
],
|
||||
),
|
||||
Expanded(
|
||||
child: TabBarView(
|
||||
children: [
|
||||
EmojiPicker(
|
||||
onEmojiSelected: controller.onEmojiSelected,
|
||||
onBackspacePressed: controller.emojiPickerBackspace,
|
||||
config: Config(
|
||||
locale: Localizations.localeOf(context),
|
||||
emojiViewConfig: EmojiViewConfig(
|
||||
noRecents: const NoRecent(),
|
||||
backgroundColor:
|
||||
theme.colorScheme.onInverseSurface,
|
||||
),
|
||||
bottomActionBarConfig: const BottomActionBarConfig(
|
||||
enabled: false,
|
||||
),
|
||||
categoryViewConfig: CategoryViewConfig(
|
||||
backspaceColor: theme.colorScheme.primary,
|
||||
iconColor: theme.colorScheme.primary.withAlpha(
|
||||
128,
|
||||
),
|
||||
iconColorSelected: theme.colorScheme.primary,
|
||||
indicatorColor: theme.colorScheme.primary,
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
),
|
||||
skinToneConfig: SkinToneConfig(
|
||||
dialogBackgroundColor: Color.lerp(
|
||||
theme.colorScheme.surface,
|
||||
theme.colorScheme.primaryContainer,
|
||||
0.75,
|
||||
)!,
|
||||
indicatorColor: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
StickerPickerDialog(
|
||||
room: controller.room,
|
||||
onSelected: (sticker) async {
|
||||
final proceed = await showTrustUserInRoomDialog(
|
||||
context,
|
||||
controller.room,
|
||||
);
|
||||
if (!proceed) return;
|
||||
controller.room.sendEvent(
|
||||
{
|
||||
'body': sticker.body,
|
||||
'info': sticker.info ?? {},
|
||||
'url': sticker.url.toString(),
|
||||
},
|
||||
type: EventTypes.Sticker,
|
||||
threadRootEventId: controller.activeThreadId,
|
||||
threadLastEventId: controller.threadLastEventId,
|
||||
);
|
||||
controller.hideEmojiPicker();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NoRecent extends StatelessWidget {
|
||||
const NoRecent({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
L10n.of(context).emoteKeyboardNoRecents,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
253
lib/pages/chat/chat_event_list.dart
Normal file
253
lib/pages/chat/chat_event_list.dart
Normal file
@@ -0,0 +1,253 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/chat.dart';
|
||||
import 'package:tatchat/pages/chat/encryption_info.dart';
|
||||
import 'package:tatchat/pages/chat/events/message.dart';
|
||||
import 'package:tatchat/pages/chat/seen_by_row.dart';
|
||||
import 'package:tatchat/pages/chat/typing_indicators.dart';
|
||||
import 'package:tatchat/utils/account_config.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/filtered_timeline_extension.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix_api_lite/model/event_types.dart';
|
||||
import 'package:scroll_to_index/scroll_to_index.dart';
|
||||
|
||||
import '../../config/app_config.dart';
|
||||
import '../../utils/date_time_extension.dart';
|
||||
|
||||
class ChatEventList extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
|
||||
const ChatEventList({super.key, required this.controller});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final timeline = controller.timeline;
|
||||
|
||||
if (timeline == null) {
|
||||
return const Center(child: CupertinoActivityIndicator());
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final colors = [theme.secondaryBubbleColor, theme.bubbleColor];
|
||||
|
||||
final horizontalPadding = FluffyThemes.isColumnMode(context) ? 8.0 : 0.0;
|
||||
|
||||
final events = timeline.events.filterByVisibleInGui(
|
||||
threadId: controller.activeThreadId,
|
||||
);
|
||||
|
||||
// create a map of eventId --> index to greatly improve performance of
|
||||
// ListView's findChildIndexCallback
|
||||
final thisEventsKeyMap = <String, int>{};
|
||||
for (var i = 0; i < events.length; i++) {
|
||||
thisEventsKeyMap[events[i].eventId] = i;
|
||||
}
|
||||
|
||||
final hasWallpaper =
|
||||
controller.room.client.applicationAccountConfig.wallpaperUrl != null;
|
||||
|
||||
return SelectionArea(
|
||||
child: MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(
|
||||
textScaler: TextScaler.linear(AppSettings.fontSizeFactor.value),
|
||||
),
|
||||
child: ListView.custom(
|
||||
padding: EdgeInsets.only(
|
||||
top: 8 + MediaQuery.paddingOf(context).top,
|
||||
bottom:
|
||||
8 +
|
||||
(controller.inputBarHeight ??
|
||||
(72 + (FluffyThemes.isColumnMode(context) ? 16 : 0))),
|
||||
left: horizontalPadding,
|
||||
right: horizontalPadding,
|
||||
),
|
||||
reverse: true,
|
||||
controller: controller.scrollController,
|
||||
keyboardDismissBehavior: PlatformInfos.isIOS
|
||||
? ScrollViewKeyboardDismissBehavior.onDrag
|
||||
: ScrollViewKeyboardDismissBehavior.manual,
|
||||
childrenDelegate: SliverChildBuilderDelegate(
|
||||
(BuildContext context, int i) {
|
||||
// Footer to display typing indicator and read receipts:
|
||||
if (i == 0) {
|
||||
if (timeline.canRequestFuture) {
|
||||
return Center(
|
||||
child: TextButton.icon(
|
||||
onPressed: timeline.isRequestingFuture
|
||||
? null
|
||||
: controller.requestFuture,
|
||||
icon: timeline.isRequestingFuture
|
||||
? CircularProgressIndicator.adaptive(strokeWidth: 2)
|
||||
: const Icon(Icons.arrow_downward_outlined),
|
||||
label: Text(L10n.of(context).loadMore),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
if (events.isNotEmpty) SeenByRow(event: events.first),
|
||||
TypingIndicators(controller),
|
||||
EncryptionInfo(room: controller.room),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Request history button or progress indicator:
|
||||
if (i == events.length + 1) {
|
||||
if (controller.activeThreadId != null ||
|
||||
!timeline.canRequestHistory) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Builder(
|
||||
builder: (context) {
|
||||
final visibleIndex = timeline.events.lastIndexWhere(
|
||||
(event) =>
|
||||
!event.isCollapsedState && event.isVisibleInGui,
|
||||
);
|
||||
if (visibleIndex > timeline.events.length - 50) {
|
||||
WidgetsBinding.instance.addPostFrameCallback(
|
||||
controller.requestHistory,
|
||||
);
|
||||
}
|
||||
return Center(
|
||||
child: TextButton.icon(
|
||||
onPressed: timeline.isRequestingHistory
|
||||
? null
|
||||
: controller.requestHistory,
|
||||
icon: timeline.isRequestingHistory
|
||||
? CircularProgressIndicator.adaptive(strokeWidth: 2)
|
||||
: const Icon(Icons.arrow_upward_outlined),
|
||||
label: Text(L10n.of(context).loadMore),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
i--;
|
||||
|
||||
// The message at this index:
|
||||
final event = events[i];
|
||||
final animateIn =
|
||||
(event.transactionId ?? event.eventId) ==
|
||||
controller.animateInEventId;
|
||||
|
||||
final nextEvent = i + 1 < events.length ? events[i + 1] : null;
|
||||
final previousEvent = i > 0 ? events[i - 1] : null;
|
||||
|
||||
// Collapsed state event
|
||||
final canExpand =
|
||||
event.isCollapsedState &&
|
||||
nextEvent?.isCollapsedState == true &&
|
||||
previousEvent?.isCollapsedState != true;
|
||||
final isCollapsed =
|
||||
event.isCollapsedState &&
|
||||
previousEvent?.isCollapsedState == true &&
|
||||
!controller.expandedEventIds.contains(event.eventId);
|
||||
|
||||
final displayDate =
|
||||
event.type == EventTypes.RoomCreate ||
|
||||
nextEvent == null ||
|
||||
!event.originServerTs.sameDay(nextEvent.originServerTs);
|
||||
|
||||
return AutoScrollTag(
|
||||
key: ValueKey(event.transactionId ?? event.eventId),
|
||||
index: i,
|
||||
controller: controller.scrollController,
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
if (!isCollapsed && displayDate)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8.0, bottom: 16.0),
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 4.0),
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius * 2,
|
||||
),
|
||||
color: theme.colorScheme.inverseSurface.withAlpha(
|
||||
200,
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
vertical: 2.0,
|
||||
),
|
||||
child: Text(
|
||||
event.originServerTs.localizedDate(context),
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.onInverseSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Message(
|
||||
event,
|
||||
bigEmojis: controller.bigEmojis,
|
||||
animateIn: animateIn,
|
||||
onSwipe: () => controller.replyAction(replyTo: event),
|
||||
onInfoTab: controller.showEventInfo,
|
||||
onMention: () => controller.sendController.text +=
|
||||
'${event.senderFromMemoryOrFallback.mention} ',
|
||||
highlightMarker:
|
||||
controller.scrollToEventIdMarker == event.eventId,
|
||||
onSelect: controller.onSelectMessage,
|
||||
scrollToEventId: controller.scrollToEventId,
|
||||
longPressSelect: controller.selectedEvents.isNotEmpty,
|
||||
selected: controller.selectedEvents.any(
|
||||
(e) => e.eventId == event.eventId,
|
||||
),
|
||||
singleSelected:
|
||||
controller.selectedEvents.singleOrNull?.eventId ==
|
||||
event.eventId,
|
||||
onEdit: controller.editSelectedEventAction,
|
||||
timeline: timeline,
|
||||
displayReadMarker:
|
||||
i > 0 &&
|
||||
controller.readMarkerEventId == event.eventId,
|
||||
nextEvent: nextEvent,
|
||||
previousEvent: previousEvent,
|
||||
wallpaperMode: hasWallpaper,
|
||||
scrollController: controller.scrollController,
|
||||
colors: colors,
|
||||
isCollapsed: isCollapsed,
|
||||
enterThread: controller.activeThreadId == null
|
||||
? controller.enterThread
|
||||
: null,
|
||||
onExpand: canExpand
|
||||
? () => controller.expandEventsFrom(
|
||||
event,
|
||||
!controller.expandedEventIds.contains(
|
||||
event.eventId,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
childCount: events.length + 2,
|
||||
findChildIndexCallback: (key) =>
|
||||
controller.findChildIndexCallback(key, thisEventsKeyMap),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
436
lib/pages/chat/chat_input_row.dart
Normal file
436
lib/pages/chat/chat_input_row.dart
Normal file
@@ -0,0 +1,436 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:emoji_picker_flutter/locales/default_emoji_set_locale.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/recording_input_row.dart';
|
||||
import 'package:tatchat/pages/chat/recording_view_model.dart';
|
||||
import 'package:tatchat/utils/other_party_can_receive.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/hover_builder.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../config/themes.dart';
|
||||
import 'chat.dart';
|
||||
import 'input_bar.dart';
|
||||
|
||||
class ChatInputRow extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
|
||||
static const double height = 56.0;
|
||||
|
||||
const ChatInputRow(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final textMessageOnly =
|
||||
controller.sendController.text.isNotEmpty ||
|
||||
controller.replyEvent != null ||
|
||||
controller.editEvent != null;
|
||||
|
||||
if (!controller.room.otherPartyCanReceiveMessages) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Text(
|
||||
L10n.of(context).otherPartyNotLoggedIn,
|
||||
style: theme.textTheme.bodySmall,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final selectedTextButtonStyle = TextButton.styleFrom(
|
||||
foregroundColor: theme.colorScheme.onTertiaryContainer,
|
||||
);
|
||||
|
||||
return RecordingViewModel(
|
||||
builder: (context, recordingViewModel) {
|
||||
if (recordingViewModel.isRecording) {
|
||||
return RecordingInputRow(
|
||||
state: recordingViewModel,
|
||||
onSend: controller.onVoiceMessageSend,
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
crossAxisAlignment: .end,
|
||||
mainAxisAlignment: .spaceBetween,
|
||||
children: controller.selectMode
|
||||
? <Widget>[
|
||||
if (controller.selectedEvents.every(
|
||||
(event) => event.status == EventStatus.error,
|
||||
))
|
||||
SizedBox(
|
||||
height: height,
|
||||
child: TextButton(
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: theme.colorScheme.error,
|
||||
),
|
||||
onPressed: controller.deleteErrorEventsAction,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
const Icon(Icons.delete_forever_outlined),
|
||||
Text(L10n.of(context).delete),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SizedBox(
|
||||
height: height,
|
||||
child: TextButton(
|
||||
style: selectedTextButtonStyle,
|
||||
onPressed: controller.forwardEventsAction,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
const Icon(Icons.keyboard_arrow_left_outlined),
|
||||
Text(L10n.of(context).forward),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
controller.selectedEvents.length == 1
|
||||
? controller.selectedEvents.first
|
||||
.getDisplayEvent(controller.timeline!)
|
||||
.status
|
||||
.isSent
|
||||
? SizedBox(
|
||||
height: height,
|
||||
child: TextButton(
|
||||
style: selectedTextButtonStyle,
|
||||
onPressed: controller.replyAction,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Text(L10n.of(context).reply),
|
||||
const Icon(Icons.keyboard_arrow_right),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
: SizedBox(
|
||||
height: height,
|
||||
child: TextButton(
|
||||
style: selectedTextButtonStyle,
|
||||
onPressed: controller.sendAgainAction,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Text(L10n.of(context).tryToSendAgain),
|
||||
const SizedBox(width: 4),
|
||||
const Icon(Icons.send_outlined, size: 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
]
|
||||
: <Widget>[
|
||||
const SizedBox(width: 8),
|
||||
AnimatedContainer(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
width: textMessageOnly ? 0 : 48,
|
||||
height: height,
|
||||
alignment: Alignment.center,
|
||||
decoration: const BoxDecoration(),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: PopupMenuButton<AddPopupMenuActions>(
|
||||
useRootNavigator: true,
|
||||
icon: const Icon(Icons.add_circle_outline),
|
||||
iconColor: theme.colorScheme.onPrimaryContainer,
|
||||
onSelected: controller.onAddPopupMenuButtonSelected,
|
||||
itemBuilder: (BuildContext context) => [
|
||||
if (PlatformInfos.isMobile)
|
||||
PopupMenuItem(
|
||||
value: AddPopupMenuActions.location,
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.onPrimaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.primaryContainer,
|
||||
child: const Icon(Icons.gps_fixed_outlined),
|
||||
),
|
||||
title: Text(L10n.of(context).shareLocation),
|
||||
contentPadding: const EdgeInsets.all(0),
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: AddPopupMenuActions.poll,
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.onPrimaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.primaryContainer,
|
||||
child: const Icon(Icons.poll_outlined),
|
||||
),
|
||||
title: Text(L10n.of(context).startPoll),
|
||||
contentPadding: const EdgeInsets.all(0),
|
||||
),
|
||||
),
|
||||
PopupMenuDivider(),
|
||||
if (PlatformInfos.isMobile) ...[
|
||||
PopupMenuItem(
|
||||
value: AddPopupMenuActions.videoCamera,
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.onPrimaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.primaryContainer,
|
||||
child: const Icon(Icons.videocam_outlined),
|
||||
),
|
||||
title: Text(L10n.of(context).recordAVideo),
|
||||
contentPadding: const EdgeInsets.all(0),
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: AddPopupMenuActions.photoCamera,
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.onPrimaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.primaryContainer,
|
||||
child: const Icon(Icons.camera_alt_outlined),
|
||||
),
|
||||
title: Text(L10n.of(context).takeAPhoto),
|
||||
contentPadding: const EdgeInsets.all(0),
|
||||
),
|
||||
),
|
||||
PopupMenuDivider(),
|
||||
],
|
||||
PopupMenuItem(
|
||||
value: AddPopupMenuActions.media,
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.onPrimaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.primaryContainer,
|
||||
child: const Icon(Icons.image_outlined),
|
||||
),
|
||||
title: Text(L10n.of(context).openGallery),
|
||||
contentPadding: const EdgeInsets.all(0),
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: AddPopupMenuActions.file,
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.onPrimaryContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.primaryContainer,
|
||||
child: const Icon(Icons.attachment_outlined),
|
||||
),
|
||||
title: Text(L10n.of(context).sendFile),
|
||||
contentPadding: const EdgeInsets.all(0),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
height: height,
|
||||
width: 48,
|
||||
alignment: Alignment.center,
|
||||
child: IconButton(
|
||||
tooltip: L10n.of(context).emojis,
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
icon: Icon(
|
||||
controller.showEmojiPicker
|
||||
? Icons.keyboard
|
||||
: Icons.add_reaction_outlined,
|
||||
key: ValueKey(controller.showEmojiPicker),
|
||||
),
|
||||
onPressed: controller.emojiPickerAction,
|
||||
),
|
||||
),
|
||||
if (Matrix.of(context).isMultiAccount &&
|
||||
Matrix.of(context).hasComplexBundles &&
|
||||
Matrix.of(context).currentBundle!.length > 1)
|
||||
Container(
|
||||
height: height,
|
||||
width: 48,
|
||||
alignment: Alignment.center,
|
||||
child: _ChatAccountPicker(controller),
|
||||
),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2.0),
|
||||
child: InputBar(
|
||||
room: controller.room,
|
||||
minLines: 1,
|
||||
maxLines: 8,
|
||||
autofocus: !PlatformInfos.isMobile,
|
||||
keyboardType: TextInputType.multiline,
|
||||
textInputAction:
|
||||
AppSettings.sendOnEnter.value == true &&
|
||||
PlatformInfos.isMobile
|
||||
? TextInputAction.send
|
||||
: null,
|
||||
onSubmitted: controller.onInputBarSubmitted,
|
||||
onSubmitImage: controller.sendImageFromClipBoard,
|
||||
focusNode: controller.inputFocus,
|
||||
controller: controller.sendController,
|
||||
decoration: InputDecoration(
|
||||
contentPadding: const EdgeInsets.only(
|
||||
left: 6.0,
|
||||
right: 6.0,
|
||||
bottom: 6.0,
|
||||
top: 3.0,
|
||||
),
|
||||
counter: const SizedBox.shrink(),
|
||||
hintText: controller.room.encrypted
|
||||
? L10n.of(context).encryptedMessage
|
||||
: L10n.of(context).unencryptedMessage,
|
||||
hintMaxLines: 1,
|
||||
border: InputBorder.none,
|
||||
enabledBorder: InputBorder.none,
|
||||
filled: false,
|
||||
),
|
||||
onChanged: controller.onInputBarChanged,
|
||||
suggestionEmojis:
|
||||
getDefaultEmojiLocale(
|
||||
AppSettings.emojiSuggestionLocale.value.isNotEmpty
|
||||
? Locale(
|
||||
AppSettings.emojiSuggestionLocale.value,
|
||||
)
|
||||
: Localizations.localeOf(context),
|
||||
).fold(
|
||||
[],
|
||||
(emojis, category) =>
|
||||
emojis..addAll(category.emoji),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
height: height,
|
||||
width: height,
|
||||
alignment: Alignment.center,
|
||||
child:
|
||||
PlatformInfos.platformCanRecord &&
|
||||
!controller.sendController.text.isNotEmpty &&
|
||||
controller.editEvent == null
|
||||
? HoverBuilder(
|
||||
builder: (context, hovered) => IconButton(
|
||||
tooltip: L10n.of(context).voiceMessage,
|
||||
onPressed: hovered
|
||||
? () => recordingViewModel.startRecording(
|
||||
controller.room,
|
||||
)
|
||||
: () => ScaffoldMessenger.of(context)
|
||||
.showSnackBar(
|
||||
SnackBar(
|
||||
margin: EdgeInsets.only(
|
||||
bottom: height + 16,
|
||||
left: 16,
|
||||
right: 16,
|
||||
top: 16,
|
||||
),
|
||||
showCloseIcon: true,
|
||||
content: Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).longPressToRecordVoiceMessage,
|
||||
),
|
||||
),
|
||||
),
|
||||
onLongPress: () => recordingViewModel
|
||||
.startRecording(controller.room),
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: theme.bubbleColor,
|
||||
foregroundColor: theme.onBubbleColor,
|
||||
),
|
||||
icon: Icon(
|
||||
hovered ? Icons.mic : Icons.mic_none_outlined,
|
||||
),
|
||||
),
|
||||
)
|
||||
: IconButton(
|
||||
key: Key('send_button'),
|
||||
tooltip: L10n.of(context).send,
|
||||
onPressed: controller.send,
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: theme.bubbleColor,
|
||||
foregroundColor: theme.onBubbleColor,
|
||||
),
|
||||
icon: const Icon(Icons.send_outlined),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ChatAccountPicker extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
|
||||
const _ChatAccountPicker(this.controller);
|
||||
|
||||
void _popupMenuButtonSelected(String mxid, BuildContext context) {
|
||||
final client = Matrix.of(
|
||||
context,
|
||||
).currentBundle!.firstWhere((cl) => cl!.userID == mxid, orElse: () => null);
|
||||
if (client == null) {
|
||||
Logs().w('Attempted to switch to a non-existing client $mxid');
|
||||
return;
|
||||
}
|
||||
controller.setSendingClient(client);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final clients = controller.currentRoomBundle;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: FutureBuilder<Profile>(
|
||||
future: controller.sendingClient.fetchOwnProfile(),
|
||||
builder: (context, snapshot) => PopupMenuButton<String>(
|
||||
useRootNavigator: true,
|
||||
onSelected: (mxid) => _popupMenuButtonSelected(mxid, context),
|
||||
itemBuilder: (BuildContext context) => clients
|
||||
.map(
|
||||
(client) => PopupMenuItem(
|
||||
value: client!.userID,
|
||||
child: FutureBuilder<Profile>(
|
||||
future: client.fetchOwnProfile(),
|
||||
builder: (context, snapshot) => ListTile(
|
||||
leading: Avatar(
|
||||
mxContent: snapshot.data?.avatarUrl,
|
||||
name:
|
||||
snapshot.data?.displayName ??
|
||||
client.userID!.localpart,
|
||||
size: 20,
|
||||
),
|
||||
title: Text(snapshot.data?.displayName ?? client.userID!),
|
||||
contentPadding: const EdgeInsets.all(0),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
child: Avatar(
|
||||
mxContent: snapshot.data?.avatarUrl,
|
||||
name:
|
||||
snapshot.data?.displayName ??
|
||||
Matrix.of(context).client.userID!.localpart,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
494
lib/pages/chat/chat_view.dart
Normal file
494
lib/pages/chat/chat_view.dart
Normal file
@@ -0,0 +1,494 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:desktop_drop/desktop_drop.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/chat.dart';
|
||||
import 'package:tatchat/pages/chat/chat_app_bar_list_tile.dart';
|
||||
import 'package:tatchat/pages/chat/chat_app_bar_title.dart';
|
||||
import 'package:tatchat/pages/chat/chat_event_list.dart';
|
||||
import 'package:tatchat/pages/chat/pinned_events.dart';
|
||||
import 'package:tatchat/pages/chat/reply_display.dart';
|
||||
import 'package:tatchat/utils/account_config.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/widgets/chat_settings_popup_menu.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:tatchat/widgets/pulsating_widget.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../utils/stream_extension.dart';
|
||||
import 'chat_emoji_picker.dart';
|
||||
import 'chat_input_row.dart';
|
||||
|
||||
enum _EventContextAction { info, report }
|
||||
|
||||
class ChatView extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
|
||||
const ChatView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final hasActiveGroupCall = controller.room.hasActiveMatrixRtcCall;
|
||||
if (controller.room.membership == Membership.invite) {
|
||||
showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => controller.room.join(),
|
||||
exceptionContext: ExceptionContext.joinRoom,
|
||||
);
|
||||
}
|
||||
final bottomSheetPadding = FluffyThemes.isColumnMode(context) ? 16.0 : 8.0;
|
||||
final scrollUpBannerEventId = controller.scrollUpBannerEventId;
|
||||
|
||||
final accountConfig = Matrix.of(context).client.applicationAccountConfig;
|
||||
|
||||
return PopScope(
|
||||
canPop:
|
||||
controller.selectedEvents.isEmpty &&
|
||||
!controller.showEmojiPicker &&
|
||||
controller.activeThreadId == null,
|
||||
onPopInvokedWithResult: (pop, _) async {
|
||||
if (pop) return;
|
||||
if (controller.selectedEvents.isNotEmpty) {
|
||||
controller.clearSelectedEvents();
|
||||
} else if (controller.showEmojiPicker) {
|
||||
controller.emojiPickerAction();
|
||||
} else if (controller.activeThreadId != null) {
|
||||
controller.closeThread();
|
||||
}
|
||||
},
|
||||
child: StreamBuilder(
|
||||
stream: controller.room.client.onRoomState.stream
|
||||
.where((update) => update.roomId == controller.room.id)
|
||||
.rateLimit(const Duration(seconds: 1)),
|
||||
builder: (context, snapshot) => FutureBuilder(
|
||||
future: controller.loadTimelineFuture,
|
||||
builder: (BuildContext context, snapshot) {
|
||||
var appbarBottomHeight = 0.0;
|
||||
final activeThreadId = controller.activeThreadId;
|
||||
if (activeThreadId != null) {
|
||||
appbarBottomHeight += ChatAppBarListTile.fixedHeight;
|
||||
}
|
||||
if (controller.room.pinnedEventIds.isNotEmpty &&
|
||||
activeThreadId == null) {
|
||||
appbarBottomHeight += ChatAppBarListTile.fixedHeight;
|
||||
}
|
||||
if (scrollUpBannerEventId != null && activeThreadId == null) {
|
||||
appbarBottomHeight += ChatAppBarListTile.fixedHeight;
|
||||
}
|
||||
return Scaffold(
|
||||
key: Key('chat_page'),
|
||||
extendBodyBehindAppBar: true,
|
||||
appBar: AppBar(
|
||||
shape: FluffyThemes.isColumnMode(context)
|
||||
? Border(
|
||||
bottom: BorderSide(color: theme.dividerColor, width: 1),
|
||||
)
|
||||
: null,
|
||||
actionsIconTheme: IconThemeData(
|
||||
color: controller.selectedEvents.isEmpty
|
||||
? null
|
||||
: theme.colorScheme.onTertiaryContainer,
|
||||
),
|
||||
backgroundColor: controller.selectedEvents.isEmpty
|
||||
? controller.activeThreadId != null
|
||||
? theme.colorScheme.secondaryContainer
|
||||
: theme.colorScheme.surface.withAlpha(240)
|
||||
: theme.colorScheme.tertiaryContainer,
|
||||
automaticallyImplyLeading: false,
|
||||
leading: controller.selectMode
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: controller.clearSelectedEvents,
|
||||
tooltip: L10n.of(context).close,
|
||||
color: theme.colorScheme.onTertiaryContainer,
|
||||
)
|
||||
: activeThreadId != null
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: controller.closeThread,
|
||||
tooltip: L10n.of(context).backToMainChat,
|
||||
color: theme.colorScheme.onSecondaryContainer,
|
||||
)
|
||||
: FluffyThemes.isColumnMode(context)
|
||||
? null
|
||||
: const Center(child: BackButton()),
|
||||
titleSpacing: FluffyThemes.isColumnMode(context) ? 24 : 0,
|
||||
title: ChatAppBarTitle(controller),
|
||||
actions: [
|
||||
if (controller.selectMode) ...[
|
||||
if (controller.canEditSelectedEvents)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit_outlined),
|
||||
tooltip: L10n.of(context).edit,
|
||||
onPressed: controller.editSelectedEventAction,
|
||||
),
|
||||
if (controller.selectedEvents.length == 1 &&
|
||||
controller.activeThreadId == null &&
|
||||
controller.room.canSendDefaultMessages)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.message_outlined),
|
||||
tooltip: L10n.of(context).replyInThread,
|
||||
onPressed: () => controller.enterThread(
|
||||
controller.selectedEvents.single.eventId,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy_outlined),
|
||||
tooltip: L10n.of(context).copyToClipboard,
|
||||
onPressed: controller.copyEventsAction,
|
||||
),
|
||||
if (controller.canRedactSelectedEvents)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outlined),
|
||||
color: theme.colorScheme.error,
|
||||
tooltip: L10n.of(context).redactMessage,
|
||||
onPressed: controller.redactEventsAction,
|
||||
),
|
||||
if (controller.selectedEvents.length == 1)
|
||||
PopupMenuButton<_EventContextAction>(
|
||||
useRootNavigator: true,
|
||||
onSelected: (action) {
|
||||
switch (action) {
|
||||
case _EventContextAction.info:
|
||||
controller.showEventInfo();
|
||||
controller.clearSelectedEvents();
|
||||
break;
|
||||
case _EventContextAction.report:
|
||||
controller.reportEventAction();
|
||||
break;
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
if (controller.canPinSelectedEvents)
|
||||
PopupMenuItem(
|
||||
onTap: controller.pinEvent,
|
||||
value: null,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
const Icon(Icons.push_pin_outlined),
|
||||
const SizedBox(width: 12),
|
||||
Text(L10n.of(context).pinMessage),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (controller.canSaveSelectedEvent)
|
||||
PopupMenuItem(
|
||||
onTap: () =>
|
||||
controller.saveSelectedEvent(context),
|
||||
value: null,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
const Icon(Icons.download_outlined),
|
||||
const SizedBox(width: 12),
|
||||
Text(L10n.of(context).downloadFile),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: _EventContextAction.info,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
const Icon(Icons.info_outlined),
|
||||
const SizedBox(width: 12),
|
||||
Text(L10n.of(context).messageInfo),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (controller.selectedEvents.single.status.isSent)
|
||||
PopupMenuItem(
|
||||
value: _EventContextAction.report,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.shield_outlined,
|
||||
color: Colors.red,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(L10n.of(context).reportMessage),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
] else if (!controller.room.isArchived) ...[
|
||||
if (hasActiveGroupCall)
|
||||
PulsatingWidget(
|
||||
color: theme.colorScheme.error,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4.0),
|
||||
child: TextButton.icon(
|
||||
icon: Icon(switch (controller
|
||||
.room
|
||||
.activeMatrixRtcCallIntent) {
|
||||
.voice => Icons.video_call_outlined,
|
||||
_ => Icons.mic_outlined,
|
||||
}),
|
||||
label: Text(
|
||||
controller.room
|
||||
.getActiveMatrixRtcMembers()
|
||||
.length
|
||||
.toString(),
|
||||
),
|
||||
onPressed:
|
||||
controller.room.hasPermissionForMatrixRtcCall
|
||||
? controller.startOrJoinVideoCall
|
||||
: null,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.error,
|
||||
foregroundColor: theme.colorScheme.onError,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (controller.room.hasPermissionForMatrixRtcCall &&
|
||||
controller.supportLiveKitCalls)
|
||||
IconButton(
|
||||
icon: Icon(Icons.call_outlined),
|
||||
onPressed: controller.startOrJoinVideoCall,
|
||||
),
|
||||
ChatSettingsPopupMenu(controller.room, true),
|
||||
],
|
||||
],
|
||||
bottom: PreferredSize(
|
||||
preferredSize: Size.fromHeight(appbarBottomHeight),
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
PinnedEvents(controller),
|
||||
if (activeThreadId != null)
|
||||
SizedBox(
|
||||
height: ChatAppBarListTile.fixedHeight,
|
||||
child: Center(
|
||||
child: TextButton.icon(
|
||||
onPressed: () =>
|
||||
controller.scrollToEventId(activeThreadId),
|
||||
icon: const Icon(Icons.message),
|
||||
label: Text(L10n.of(context).replyInThread),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor:
|
||||
theme.colorScheme.onSecondaryContainer,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (scrollUpBannerEventId != null &&
|
||||
activeThreadId == null)
|
||||
ChatAppBarListTile(
|
||||
leading: IconButton(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: L10n.of(context).close,
|
||||
onPressed: () {
|
||||
controller.discardScrollUpBannerEventId();
|
||||
controller.setReadMarker();
|
||||
},
|
||||
),
|
||||
title: L10n.of(context).jumpToLastReadMessage,
|
||||
trailing: TextButton(
|
||||
onPressed: () {
|
||||
controller.scrollToEventId(scrollUpBannerEventId);
|
||||
controller.discardScrollUpBannerEventId();
|
||||
},
|
||||
child: Text(L10n.of(context).jump),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
floatingActionButton:
|
||||
controller.showScrollDownButton &&
|
||||
controller.selectedEvents.isEmpty
|
||||
? Padding(
|
||||
padding: EdgeInsets.only(
|
||||
bottom: theme.appBarTheme.toolbarHeight ?? 56,
|
||||
),
|
||||
child: FloatingActionButton(
|
||||
onPressed: controller.scrollDown,
|
||||
heroTag: null,
|
||||
mini: true,
|
||||
backgroundColor: theme.colorScheme.surface,
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
child: const Icon(Icons.arrow_downward_outlined),
|
||||
),
|
||||
)
|
||||
: null,
|
||||
body: NotificationListener<SizeChangedLayoutNotification>(
|
||||
onNotification: (SizeChangedLayoutNotification notification) {
|
||||
WidgetsBinding.instance.addPostFrameCallback(
|
||||
(_) => controller.updateInputBarHeight(),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
child: DropTarget(
|
||||
onDragDone: controller.onDragDone,
|
||||
onDragEntered: controller.onDragEntered,
|
||||
onDragExited: controller.onDragExited,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: Stack(
|
||||
children: <Widget>[
|
||||
if (accountConfig.wallpaperUrl != null)
|
||||
Opacity(
|
||||
opacity: accountConfig.wallpaperOpacity ?? 0.5,
|
||||
child: ImageFiltered(
|
||||
imageFilter: ui.ImageFilter.blur(
|
||||
sigmaX: accountConfig.wallpaperBlur ?? 0.0,
|
||||
sigmaY: accountConfig.wallpaperBlur ?? 0.0,
|
||||
),
|
||||
child: MxcImage(
|
||||
cacheKey: accountConfig.wallpaperUrl.toString(),
|
||||
uri: accountConfig.wallpaperUrl,
|
||||
fit: BoxFit.cover,
|
||||
height: MediaQuery.sizeOf(context).height,
|
||||
width: MediaQuery.sizeOf(context).width,
|
||||
isThumbnail: false,
|
||||
placeholder: (_) => Container(),
|
||||
),
|
||||
),
|
||||
),
|
||||
GestureDetector(
|
||||
onTap: controller.clearSingleSelectedEvent,
|
||||
child: ChatEventList(controller: controller),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: SizeChangedLayoutNotifier(
|
||||
child: Container(
|
||||
key: controller.inputBarKey,
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
theme.colorScheme.surface.withAlpha(0),
|
||||
theme.colorScheme.surface,
|
||||
theme.colorScheme.surface,
|
||||
],
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
),
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Container(
|
||||
margin: EdgeInsets.all(bottomSheetPadding),
|
||||
constraints: const BoxConstraints(
|
||||
maxWidth: FluffyThemes.maxTimelineWidth,
|
||||
),
|
||||
child: controller.room.isExtinct
|
||||
? ElevatedButton.icon(
|
||||
icon: const Icon(Icons.chevron_right),
|
||||
label: Text(
|
||||
L10n.of(context).enterNewChat,
|
||||
),
|
||||
onPressed: controller.goToNewRoomAction,
|
||||
)
|
||||
: controller.room.canSendDefaultMessages &&
|
||||
controller.room.membership ==
|
||||
Membership.join
|
||||
? Material(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
color:
|
||||
controller.selectedEvents.isNotEmpty
|
||||
? theme
|
||||
.colorScheme
|
||||
.tertiaryContainer
|
||||
: theme
|
||||
.colorScheme
|
||||
.surfaceContainer,
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
child:
|
||||
controller.room.isAbandonedDMRoom ==
|
||||
true
|
||||
? Row(
|
||||
mainAxisAlignment: .spaceEvenly,
|
||||
children: [
|
||||
TextButton.icon(
|
||||
style: TextButton.styleFrom(
|
||||
padding:
|
||||
const EdgeInsets.all(
|
||||
16,
|
||||
),
|
||||
foregroundColor: theme
|
||||
.colorScheme
|
||||
.error,
|
||||
),
|
||||
icon: const Icon(
|
||||
Icons.archive_outlined,
|
||||
),
|
||||
onPressed:
|
||||
controller.leaveChat,
|
||||
label: Text(
|
||||
L10n.of(context).leave,
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
style: TextButton.styleFrom(
|
||||
padding:
|
||||
const EdgeInsets.all(
|
||||
16,
|
||||
),
|
||||
),
|
||||
icon: const Icon(
|
||||
Icons.forum_outlined,
|
||||
),
|
||||
onPressed:
|
||||
controller.recreateChat,
|
||||
label: Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).reopenChat,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
ReplyDisplay(controller),
|
||||
ChatInputRow(controller),
|
||||
ChatEmojiPicker(controller),
|
||||
],
|
||||
),
|
||||
)
|
||||
: SizedBox.shrink(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (controller.dragging)
|
||||
Container(
|
||||
color: theme.scaffoldBackgroundColor.withAlpha(230),
|
||||
alignment: Alignment.center,
|
||||
child: const Icon(Icons.upload_outlined, size: 100),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
95
lib/pages/chat/command_hints.dart
Normal file
95
lib/pages/chat/command_hints.dart
Normal file
@@ -0,0 +1,95 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// This file is auto-generated using scripts/generate_command_hints_glue.sh.
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
|
||||
String commandExample(String command) {
|
||||
switch (command) {
|
||||
case 'markasdm':
|
||||
case 'kick':
|
||||
case 'dm':
|
||||
case 'ban':
|
||||
case 'unban':
|
||||
case 'ignore':
|
||||
case 'unignore':
|
||||
case 'invite':
|
||||
return '/$command <matrix-id>';
|
||||
case 'html':
|
||||
case 'sendraw':
|
||||
case 'plain':
|
||||
return '/$command <message>';
|
||||
case 'op':
|
||||
return '/$command <matrix-id> <power-level>';
|
||||
default:
|
||||
return '/$command';
|
||||
}
|
||||
}
|
||||
|
||||
String commandHint(L10n l10n, String command) {
|
||||
switch (command) {
|
||||
case 'ban':
|
||||
return l10n.commandHint_ban;
|
||||
case 'clearcache':
|
||||
return l10n.commandHint_clearcache;
|
||||
case 'create':
|
||||
return l10n.commandHint_create;
|
||||
case 'discardsession':
|
||||
return l10n.commandHint_discardsession;
|
||||
case 'dm':
|
||||
return l10n.commandHint_dm;
|
||||
case 'html':
|
||||
return l10n.commandHint_html;
|
||||
case 'invite':
|
||||
return l10n.commandHint_invite;
|
||||
case 'join':
|
||||
return l10n.commandHint_join;
|
||||
case 'kick':
|
||||
return l10n.commandHint_kick;
|
||||
case 'leave':
|
||||
return l10n.commandHint_leave;
|
||||
case 'me':
|
||||
return l10n.commandHint_me;
|
||||
case 'myroomavatar':
|
||||
return l10n.commandHint_myroomavatar;
|
||||
case 'myroomnick':
|
||||
return l10n.commandHint_myroomnick;
|
||||
case 'op':
|
||||
return l10n.commandHint_op;
|
||||
case 'plain':
|
||||
return l10n.commandHint_plain;
|
||||
case 'react':
|
||||
return l10n.commandHint_react;
|
||||
case 'send':
|
||||
return l10n.commandHint_send;
|
||||
case 'unban':
|
||||
return l10n.commandHint_unban;
|
||||
case 'markasdm':
|
||||
return l10n.commandHint_markasdm;
|
||||
case 'markasgroup':
|
||||
return l10n.commandHint_markasgroup;
|
||||
case 'googly':
|
||||
return l10n.commandHint_googly;
|
||||
case 'hug':
|
||||
return l10n.commandHint_hug;
|
||||
case 'cuddle':
|
||||
return l10n.commandHint_cuddle;
|
||||
case 'sendraw':
|
||||
return l10n.commandHint_sendraw;
|
||||
case 'ignore':
|
||||
return l10n.commandHint_ignore;
|
||||
case 'unignore':
|
||||
return l10n.commandHint_unignore;
|
||||
case 'roomupgrade':
|
||||
return l10n.commandHint_roomupgrade;
|
||||
case 'logout':
|
||||
return l10n.commandHint_logout;
|
||||
case 'logoutall':
|
||||
return l10n.commandHint_logoutall;
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
107
lib/pages/chat/encryption_info.dart
Normal file
107
lib/pages/chat/encryption_info.dart
Normal file
@@ -0,0 +1,107 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class EncryptionInfo extends StatelessWidget {
|
||||
final Room room;
|
||||
|
||||
const EncryptionInfo({super.key, required this.room});
|
||||
|
||||
Future<int> _unverifiedDevices() async {
|
||||
if (!room.encrypted) return 0;
|
||||
final users = await room.requestParticipants();
|
||||
final devicesKeysLists = users
|
||||
.map((user) => room.client.userDeviceKeys[user.id])
|
||||
.nonNulls;
|
||||
final devices = devicesKeysLists.fold<List<DeviceKeys>>(
|
||||
[],
|
||||
(devices, devicesKeysList) => [
|
||||
...devices,
|
||||
...devicesKeysList.deviceKeys.values,
|
||||
],
|
||||
);
|
||||
return devices
|
||||
.where(
|
||||
(device) =>
|
||||
!device.verified &&
|
||||
!device.blocked &&
|
||||
!device.hasValidSignatureChain(verifiedByTheirMasterKey: true) &&
|
||||
device.encryptToDevice,
|
||||
)
|
||||
.length;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AnimatedSize(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: FutureBuilder(
|
||||
future: _unverifiedDevices(),
|
||||
builder: (context, asyncSnapshot) {
|
||||
final unverifiedDevices = asyncSnapshot.data ?? 0;
|
||||
if (unverifiedDevices == 0) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: Material(
|
||||
color: theme.colorScheme.surface.withAlpha(128),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius / 3,
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
vertical: 4.0,
|
||||
),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
WidgetSpan(
|
||||
child: Icon(Icons.lock_person_outlined, size: 13),
|
||||
),
|
||||
TextSpan(text: ' '),
|
||||
TextSpan(
|
||||
text: L10n.of(
|
||||
context,
|
||||
).countUnverifiedDevices(unverifiedDevices),
|
||||
),
|
||||
TextSpan(text: ' '),
|
||||
TextSpan(
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: theme.colorScheme.primary,
|
||||
),
|
||||
recognizer: TapGestureRecognizer()
|
||||
..onTap = () =>
|
||||
context.go('/rooms/${room.id}/encryption'),
|
||||
text: 'Check',
|
||||
),
|
||||
],
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 11),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
108
lib/pages/chat/event_info_dialog.dart
Normal file
108
lib/pages/chat/event_info_dialog.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/adaptive_bottom_sheet.dart';
|
||||
import 'package:tatchat/utils/date_time_extension.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
extension EventInfoDialogExtension on Event {
|
||||
void showInfoDialog(BuildContext context) => showAdaptiveBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => EventInfoDialog(l10n: L10n.of(context), event: this),
|
||||
);
|
||||
}
|
||||
|
||||
class EventInfoDialog extends StatelessWidget {
|
||||
final Event event;
|
||||
final L10n l10n;
|
||||
|
||||
const EventInfoDialog({required this.event, required this.l10n, super.key});
|
||||
|
||||
String prettyJson(MatrixEvent event) {
|
||||
const decoder = JsonDecoder();
|
||||
const encoder = JsonEncoder.withIndent(' ');
|
||||
final object = decoder.convert(jsonEncode(event.toJson()));
|
||||
return encoder.convert(object);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final originalSource = event.originalSource;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(L10n.of(context).messageInfo),
|
||||
leading: CloseButton(
|
||||
onPressed: Navigator.of(context, rootNavigator: false).pop,
|
||||
),
|
||||
),
|
||||
body: ListView(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: Avatar(
|
||||
mxContent: event.senderFromMemoryOrFallback.avatarUrl,
|
||||
name: event.senderFromMemoryOrFallback.calcDisplayname(),
|
||||
client: event.room.client,
|
||||
presenceUserId: event.senderId,
|
||||
),
|
||||
title: Text(L10n.of(context).sender),
|
||||
subtitle: Text(
|
||||
'${event.senderFromMemoryOrFallback.calcDisplayname()} [${event.senderId}]',
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
title: Text('${L10n.of(context).time}:'),
|
||||
subtitle: Text(event.originServerTs.localizedTime(context)),
|
||||
),
|
||||
ListTile(
|
||||
title: Text('${L10n.of(context).status}:'),
|
||||
subtitle: Text(event.status.name),
|
||||
),
|
||||
ListTile(title: Text('${L10n.of(context).sourceCode}:')),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
color: theme.colorScheme.surfaceContainer,
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: SelectableText(
|
||||
prettyJson(MatrixEvent.fromJson(event.toJson())),
|
||||
style: TextStyle(color: theme.colorScheme.onSurface),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (event.messageType != MessageTypes.BadEncrypted &&
|
||||
originalSource != null) ...[
|
||||
ListTile(title: Text('${L10n.of(context).encrypted}:')),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
color: theme.colorScheme.surfaceContainer,
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: SelectableText(
|
||||
prettyJson(originalSource),
|
||||
style: TextStyle(color: theme.colorScheme.onSurface),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
538
lib/pages/chat/events/audio_player.dart
Normal file
538
lib/pages/chat/events/audio_player.dart
Normal file
@@ -0,0 +1,538 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:async/async.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/utils/error_reporter.dart';
|
||||
import 'package:tatchat/utils/file_description.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:ogg_caf_converter/ogg_caf_converter.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../../../utils/matrix_sdk_extensions/event_extension.dart';
|
||||
import '../../../widgets/tatu_chat_app.dart';
|
||||
import '../../../widgets/matrix.dart';
|
||||
|
||||
class AudioPlayerWidget extends StatefulWidget {
|
||||
final Color color;
|
||||
final Color linkColor;
|
||||
final double fontSize;
|
||||
final Event event;
|
||||
|
||||
static const int wavesCount = 40;
|
||||
|
||||
const AudioPlayerWidget(
|
||||
this.event, {
|
||||
required this.color,
|
||||
required this.linkColor,
|
||||
required this.fontSize,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
AudioPlayerState createState() => AudioPlayerState();
|
||||
}
|
||||
|
||||
enum AudioPlayerStatus { notDownloaded, downloading, downloaded }
|
||||
|
||||
class AudioPlayerState extends State<AudioPlayerWidget> {
|
||||
static const double buttonSize = 36;
|
||||
|
||||
AudioPlayerStatus status = AudioPlayerStatus.notDownloaded;
|
||||
double? _downloadProgress;
|
||||
|
||||
late final MatrixState matrix;
|
||||
List<int>? _waveform;
|
||||
String? _durationString;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
super.dispose();
|
||||
final audioPlayer = matrix.voiceMessageEventId.value != widget.event.eventId
|
||||
? null
|
||||
: matrix.audioPlayer;
|
||||
if (audioPlayer != null) {
|
||||
if (audioPlayer.playing && !audioPlayer.isAtEndPosition) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ScaffoldMessenger.of(matrix.context).showMaterialBanner(
|
||||
MaterialBanner(
|
||||
padding: EdgeInsets.zero,
|
||||
leading: StreamBuilder(
|
||||
stream: audioPlayer.playerStateStream.asBroadcastStream(),
|
||||
builder: (context, _) => IconButton(
|
||||
onPressed: () {
|
||||
if (audioPlayer.isAtEndPosition) {
|
||||
audioPlayer.seek(Duration.zero);
|
||||
} else if (audioPlayer.playing) {
|
||||
audioPlayer.pause();
|
||||
} else {
|
||||
audioPlayer.play();
|
||||
}
|
||||
},
|
||||
icon: audioPlayer.playing && !audioPlayer.isAtEndPosition
|
||||
? const Icon(Icons.pause_outlined)
|
||||
: const Icon(Icons.play_arrow_outlined),
|
||||
),
|
||||
),
|
||||
content: StreamBuilder(
|
||||
stream: audioPlayer.positionStream.asBroadcastStream(),
|
||||
builder: (context, _) => GestureDetector(
|
||||
onTap: () => TatuChatApp.router.go(
|
||||
'/rooms/${widget.event.room.id}?event=${widget.event.eventId}',
|
||||
),
|
||||
child: Text(
|
||||
'🎙️ ${audioPlayer.position.minuteSecondString} / ${audioPlayer.duration?.minuteSecondString} - ${widget.event.senderFromMemoryOrFallback.calcDisplayname()}',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
onPressed: () {
|
||||
audioPlayer.pause();
|
||||
audioPlayer.dispose();
|
||||
matrix.voiceMessageEventId.value = matrix.audioPlayer =
|
||||
null;
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ScaffoldMessenger.of(
|
||||
matrix.context,
|
||||
).clearMaterialBanners();
|
||||
});
|
||||
},
|
||||
icon: const Icon(Icons.close_outlined),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
audioPlayer.pause();
|
||||
audioPlayer.dispose();
|
||||
matrix.voiceMessageEventId.value = matrix.audioPlayer = null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onButtonTap() async {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ScaffoldMessenger.of(matrix.context).clearMaterialBanners();
|
||||
});
|
||||
final currentPlayer =
|
||||
matrix.voiceMessageEventId.value != widget.event.eventId
|
||||
? null
|
||||
: matrix.audioPlayer;
|
||||
if (currentPlayer != null && !currentPlayer.isAtEndPosition) {
|
||||
if (currentPlayer.playing) {
|
||||
currentPlayer.pause();
|
||||
} else {
|
||||
currentPlayer.play();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
matrix.voiceMessageEventId.value = widget.event.eventId;
|
||||
matrix.audioPlayer
|
||||
?..stop()
|
||||
..dispose();
|
||||
File? file;
|
||||
MatrixFile? matrixFile;
|
||||
|
||||
setState(() => status = AudioPlayerStatus.downloading);
|
||||
try {
|
||||
final fileSize = widget.event.content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<int>('size');
|
||||
matrixFile = await widget.event.downloadAndDecryptAttachment(
|
||||
onDownloadProgress: fileSize != null && fileSize > 0
|
||||
? (progress) {
|
||||
final progressPercentage = progress / fileSize;
|
||||
setState(() {
|
||||
_downloadProgress = progressPercentage < 1
|
||||
? progressPercentage
|
||||
: null;
|
||||
});
|
||||
}
|
||||
: null,
|
||||
);
|
||||
|
||||
final attachmentUrl = widget.event.attachmentOrThumbnailMxcUrl();
|
||||
|
||||
if (!kIsWeb && attachmentUrl != null) {
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final fileName = Uri.encodeComponent(attachmentUrl.pathSegments.last);
|
||||
file = File('${tempDir.path}/${fileName}_${matrixFile.name}');
|
||||
|
||||
await file.writeAsBytes(matrixFile.bytes);
|
||||
|
||||
if (Platform.isIOS &&
|
||||
matrixFile.mimeType.toLowerCase() == 'audio/ogg') {
|
||||
Logs().v('Convert ogg audio file for iOS...');
|
||||
final convertedFile = File('${file.path}.caf');
|
||||
if (await convertedFile.exists() == false) {
|
||||
await OggCafConverter().convertOggToCaf(
|
||||
input: file.path,
|
||||
output: convertedFile.path,
|
||||
);
|
||||
}
|
||||
file = convertedFile;
|
||||
}
|
||||
}
|
||||
|
||||
setState(() {
|
||||
status = AudioPlayerStatus.downloaded;
|
||||
});
|
||||
} catch (e, s) {
|
||||
Logs().v('Could not download audio file', e, s);
|
||||
if (!mounted) rethrow;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
rethrow;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
if (matrix.voiceMessageEventId.value != widget.event.eventId) return;
|
||||
|
||||
final audioPlayer = matrix.audioPlayer = AudioPlayer();
|
||||
|
||||
if (file != null) {
|
||||
audioPlayer.setFilePath(file.path);
|
||||
} else {
|
||||
await audioPlayer.setAudioSource(
|
||||
AudioSource.uri(
|
||||
Uri.dataFromBytes(matrixFile.bytes, mimeType: matrixFile.mimeType),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!mounted) return;
|
||||
|
||||
audioPlayer.play().onError(
|
||||
ErrorReporter(context, 'Unable to play audio message').onErrorCallback,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _toggleSpeed() async {
|
||||
final audioPlayer = matrix.audioPlayer;
|
||||
if (audioPlayer == null) return;
|
||||
switch (audioPlayer.speed) {
|
||||
case 1.0:
|
||||
await audioPlayer.setSpeed(1.25);
|
||||
break;
|
||||
case 1.25:
|
||||
await audioPlayer.setSpeed(1.5);
|
||||
break;
|
||||
case 1.5:
|
||||
await audioPlayer.setSpeed(2.0);
|
||||
break;
|
||||
case 2.0:
|
||||
await audioPlayer.setSpeed(0.5);
|
||||
break;
|
||||
case 0.5:
|
||||
default:
|
||||
await audioPlayer.setSpeed(1.0);
|
||||
break;
|
||||
}
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
List<int>? _getWaveform() {
|
||||
final eventWaveForm = widget.event.content
|
||||
.tryGetMap<String, Object?>('org.matrix.msc1767.audio')
|
||||
?.tryGetList<int>('waveform');
|
||||
if (eventWaveForm == null || eventWaveForm.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
while (eventWaveForm.length < AudioPlayerWidget.wavesCount) {
|
||||
for (var i = 0; i < eventWaveForm.length; i = i + 2) {
|
||||
eventWaveForm.insert(i, eventWaveForm[i]);
|
||||
}
|
||||
}
|
||||
var i = 0;
|
||||
final step = (eventWaveForm.length / AudioPlayerWidget.wavesCount).round();
|
||||
while (eventWaveForm.length > AudioPlayerWidget.wavesCount) {
|
||||
eventWaveForm.removeAt(i);
|
||||
i = (i + step) % AudioPlayerWidget.wavesCount;
|
||||
}
|
||||
return eventWaveForm.map((i) => i > 1024 ? 1024 : i).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
matrix = Matrix.of(context);
|
||||
_waveform = _getWaveform();
|
||||
|
||||
if (matrix.voiceMessageEventId.value == widget.event.eventId &&
|
||||
matrix.audioPlayer != null) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ScaffoldMessenger.of(matrix.context).clearMaterialBanners();
|
||||
});
|
||||
}
|
||||
|
||||
final durationInt = widget.event.content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<int>('duration');
|
||||
if (durationInt != null) {
|
||||
final duration = Duration(milliseconds: durationInt);
|
||||
_durationString = duration.minuteSecondString;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final waveform = _waveform;
|
||||
|
||||
return ValueListenableBuilder(
|
||||
valueListenable: matrix.voiceMessageEventId,
|
||||
builder: (context, eventId, _) {
|
||||
final audioPlayer = eventId != widget.event.eventId
|
||||
? null
|
||||
: matrix.audioPlayer;
|
||||
|
||||
final fileDescription = widget.event.fileDescription;
|
||||
|
||||
return StreamBuilder<Object>(
|
||||
stream: audioPlayer == null
|
||||
? null
|
||||
: StreamGroup.merge([
|
||||
audioPlayer.positionStream.asBroadcastStream(),
|
||||
audioPlayer.playerStateStream.asBroadcastStream(),
|
||||
]),
|
||||
builder: (context, _) {
|
||||
final maxPosition =
|
||||
audioPlayer?.duration?.inMilliseconds.toDouble() ?? 1.0;
|
||||
var currentPosition =
|
||||
audioPlayer?.position.inMilliseconds.toDouble() ?? 0.0;
|
||||
if (currentPosition > maxPosition) currentPosition = maxPosition;
|
||||
|
||||
final wavePosition =
|
||||
(currentPosition / maxPosition) * AudioPlayerWidget.wavesCount;
|
||||
|
||||
final statusText = audioPlayer == null
|
||||
? _durationString ?? '00:00'
|
||||
: audioPlayer.position.minuteSecondString;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
crossAxisAlignment: .start,
|
||||
children: [
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
maxWidth: FluffyThemes.columnWidth,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: <Widget>[
|
||||
SizedBox(
|
||||
width: buttonSize,
|
||||
height: buttonSize,
|
||||
child: status == AudioPlayerStatus.downloading
|
||||
? CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: widget.color,
|
||||
value: _downloadProgress,
|
||||
)
|
||||
: InkWell(
|
||||
borderRadius: BorderRadius.circular(64),
|
||||
onLongPress: () =>
|
||||
widget.event.saveFile(context),
|
||||
onTap: _onButtonTap,
|
||||
child: Material(
|
||||
color: widget.color.withAlpha(64),
|
||||
borderRadius: BorderRadius.circular(64),
|
||||
child: Icon(
|
||||
audioPlayer?.playing == true &&
|
||||
audioPlayer?.isAtEndPosition ==
|
||||
false
|
||||
? Icons.pause_outlined
|
||||
: Icons.play_arrow_outlined,
|
||||
color: widget.color,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Stack(
|
||||
children: [
|
||||
if (waveform != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
for (
|
||||
var i = 0;
|
||||
i < AudioPlayerWidget.wavesCount;
|
||||
i++
|
||||
)
|
||||
Expanded(
|
||||
child: Container(
|
||||
height: 32,
|
||||
alignment: Alignment.center,
|
||||
child: Container(
|
||||
margin:
|
||||
const EdgeInsets.symmetric(
|
||||
horizontal: 1,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: i < wavePosition
|
||||
? widget.color
|
||||
: widget.color.withAlpha(
|
||||
128,
|
||||
),
|
||||
borderRadius:
|
||||
BorderRadius.circular(64),
|
||||
),
|
||||
height: 32 * (waveform[i] / 1024),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 32,
|
||||
child: Slider(
|
||||
thumbColor:
|
||||
widget.event.senderId ==
|
||||
widget.event.room.client.userID
|
||||
? theme.colorScheme.onPrimary
|
||||
: theme.colorScheme.primary,
|
||||
activeColor: waveform == null
|
||||
? widget.color
|
||||
: Colors.transparent,
|
||||
inactiveColor: waveform == null
|
||||
? widget.color.withAlpha(128)
|
||||
: Colors.transparent,
|
||||
max: maxPosition,
|
||||
value: currentPosition,
|
||||
onChanged: (position) => audioPlayer == null
|
||||
? _onButtonTap()
|
||||
: audioPlayer.seek(
|
||||
Duration(
|
||||
milliseconds: position.round(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
SizedBox(
|
||||
width: 36,
|
||||
child: Text(
|
||||
statusText,
|
||||
style: TextStyle(color: widget.color, fontSize: 12),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
AnimatedCrossFade(
|
||||
firstChild: Padding(
|
||||
padding: const EdgeInsets.only(right: 8.0),
|
||||
child: Icon(
|
||||
Icons.mic_none_outlined,
|
||||
color: widget.color,
|
||||
),
|
||||
),
|
||||
secondChild: Material(
|
||||
color: widget.color.withAlpha(64),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius,
|
||||
),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius,
|
||||
),
|
||||
onTap: _toggleSpeed,
|
||||
child: SizedBox(
|
||||
width: 32,
|
||||
height: 20,
|
||||
child: Center(
|
||||
child: Text(
|
||||
'${audioPlayer?.speed}x',
|
||||
style: TextStyle(
|
||||
color: widget.color,
|
||||
fontSize: 9,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
crossFadeState: audioPlayer == null
|
||||
? CrossFadeState.showFirst
|
||||
: CrossFadeState.showSecond,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (fileDescription != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 8,
|
||||
),
|
||||
child: Linkify(
|
||||
text: fileDescription,
|
||||
textScaleFactor: MediaQuery.textScalerOf(
|
||||
context,
|
||||
).scale(1),
|
||||
style: TextStyle(
|
||||
color: widget.color,
|
||||
fontSize: widget.fontSize,
|
||||
),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: TextStyle(
|
||||
color: widget.linkColor,
|
||||
fontSize: widget.fontSize,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: widget.linkColor,
|
||||
),
|
||||
onOpen: (url) =>
|
||||
UrlLauncher(context, url.url).launchUrl(),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension on AudioPlayer {
|
||||
bool get isAtEndPosition {
|
||||
final duration = this.duration;
|
||||
if (duration == null) return true;
|
||||
return position >= duration;
|
||||
}
|
||||
}
|
||||
|
||||
extension on Duration {
|
||||
String get minuteSecondString =>
|
||||
'${inMinutes.toString().padLeft(2, '0')}:${(inSeconds % 60).toString().padLeft(2, '0')}';
|
||||
}
|
||||
195
lib/pages/chat/events/cute_events.dart
Normal file
195
lib/pages/chat/events/cute_events.dart
Normal file
@@ -0,0 +1,195 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class CuteContent extends StatefulWidget {
|
||||
final Event event;
|
||||
|
||||
const CuteContent(this.event, {super.key});
|
||||
|
||||
@override
|
||||
State<CuteContent> createState() => _CuteContentState();
|
||||
}
|
||||
|
||||
class _CuteContentState extends State<CuteContent> {
|
||||
static bool _isOverlayShown = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
if (AppSettings.autoplayImages.value && !_isOverlayShown) {
|
||||
addOverlay();
|
||||
}
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<User?>(
|
||||
future: widget.event.fetchSenderUser(),
|
||||
builder: (context, snapshot) {
|
||||
final label = generateLabel(snapshot.data);
|
||||
|
||||
return GestureDetector(
|
||||
onTap: addOverlay,
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
mainAxisAlignment: .center,
|
||||
children: [
|
||||
Text(widget.event.text, style: const TextStyle(fontSize: 150)),
|
||||
if (label != null) Text(label),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> addOverlay() async {
|
||||
_isOverlayShown = true;
|
||||
await Future.delayed(const Duration(milliseconds: 50));
|
||||
if (!mounted) return;
|
||||
|
||||
OverlayEntry? overlay;
|
||||
overlay = OverlayEntry(
|
||||
builder: (context) => CuteEventOverlay(
|
||||
emoji: widget.event.text,
|
||||
onAnimationEnd: () {
|
||||
_isOverlayShown = false;
|
||||
overlay?.remove();
|
||||
},
|
||||
),
|
||||
);
|
||||
Overlay.of(context).insert(overlay);
|
||||
}
|
||||
|
||||
String? generateLabel(User? user) {
|
||||
switch (widget.event.content['cute_type']) {
|
||||
case 'googly_eyes':
|
||||
return L10n.of(context).googlyEyesContent(
|
||||
user?.displayName ??
|
||||
widget.event.senderFromMemoryOrFallback.displayName ??
|
||||
'',
|
||||
);
|
||||
case 'cuddle':
|
||||
return L10n.of(context).cuddleContent(
|
||||
user?.displayName ??
|
||||
widget.event.senderFromMemoryOrFallback.displayName ??
|
||||
'',
|
||||
);
|
||||
case 'hug':
|
||||
return L10n.of(context).hugContent(
|
||||
user?.displayName ??
|
||||
widget.event.senderFromMemoryOrFallback.displayName ??
|
||||
'',
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class CuteEventOverlay extends StatefulWidget {
|
||||
final String emoji;
|
||||
final VoidCallback onAnimationEnd;
|
||||
|
||||
const CuteEventOverlay({
|
||||
super.key,
|
||||
required this.emoji,
|
||||
required this.onAnimationEnd,
|
||||
});
|
||||
|
||||
@override
|
||||
State<CuteEventOverlay> createState() => _CuteEventOverlayState();
|
||||
}
|
||||
|
||||
class _CuteEventOverlayState extends State<CuteEventOverlay>
|
||||
with TickerProviderStateMixin {
|
||||
final List<Size> items = List.generate(
|
||||
50,
|
||||
(index) => Size(Random().nextDouble(), 4 + (Random().nextDouble() * 4)),
|
||||
);
|
||||
|
||||
AnimationController? controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
controller = AnimationController(
|
||||
duration: const Duration(milliseconds: 2500),
|
||||
vsync: this,
|
||||
);
|
||||
controller?.forward();
|
||||
controller?.addStatusListener(_hideOverlay);
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: controller!,
|
||||
builder: (context, _) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth - _CuteOverlayContent.size;
|
||||
final height = constraints.maxHeight + _CuteOverlayContent.size;
|
||||
return SizedBox(
|
||||
height: constraints.maxHeight,
|
||||
width: constraints.maxWidth,
|
||||
child: OverflowBox(
|
||||
child: Stack(
|
||||
alignment: Alignment.bottomLeft,
|
||||
fit: StackFit.expand,
|
||||
children: items
|
||||
.map(
|
||||
(position) => Positioned(
|
||||
left: position.width * width,
|
||||
bottom:
|
||||
(height *
|
||||
.25 *
|
||||
position.height *
|
||||
(controller?.value ?? 0)) -
|
||||
_CuteOverlayContent.size,
|
||||
child: _CuteOverlayContent(emoji: widget.emoji),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _hideOverlay(AnimationStatus status) {
|
||||
if (status == AnimationStatus.completed) {
|
||||
widget.onAnimationEnd.call();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
controller?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class _CuteOverlayContent extends StatelessWidget {
|
||||
static const double size = 64.0;
|
||||
final String emoji;
|
||||
|
||||
const _CuteOverlayContent({required this.emoji});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox.square(
|
||||
dimension: size,
|
||||
child: Text(emoji, style: const TextStyle(fontSize: 48)),
|
||||
);
|
||||
}
|
||||
}
|
||||
35
lib/pages/chat/events/file_send_status_indicator.dart
Normal file
35
lib/pages/chat/events/file_send_status_indicator.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class FileSendStatusIndicator extends StatelessWidget {
|
||||
final FileSendingStatus fileSendingStatus;
|
||||
const FileSendStatusIndicator({super.key, required this.fileSendingStatus});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CircleAvatar(
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
switch (fileSendingStatus) {
|
||||
FileSendingStatus.generatingThumbnail => Icon(
|
||||
Icons.compress_outlined,
|
||||
size: 18,
|
||||
),
|
||||
FileSendingStatus.encrypting => Icon(Icons.lock_outlined, size: 18),
|
||||
FileSendingStatus.uploading => Icon(
|
||||
Icons.upload_outlined,
|
||||
size: 18,
|
||||
),
|
||||
},
|
||||
const CircularProgressIndicator(strokeWidth: 3),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
743
lib/pages/chat/events/html_message.dart
Normal file
743
lib/pages/chat/events/html_message.dart
Normal file
@@ -0,0 +1,743 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/code_highlight_theme.dart';
|
||||
import 'package:tatchat/utils/event_checkbox_extension.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:highlight/highlight.dart' show highlight;
|
||||
import 'package:html/dom.dart' as dom;
|
||||
import 'package:html/parser.dart' as parser;
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../../utils/url_launcher.dart';
|
||||
|
||||
class HtmlMessage extends StatelessWidget {
|
||||
final String html;
|
||||
final Room room;
|
||||
final Color textColor;
|
||||
final double fontSize;
|
||||
final TextStyle linkStyle;
|
||||
final void Function(LinkableElement) onOpen;
|
||||
final String? eventId;
|
||||
final Set<Event>? checkboxCheckedEvents;
|
||||
|
||||
const HtmlMessage({
|
||||
super.key,
|
||||
required this.html,
|
||||
required this.room,
|
||||
required this.fontSize,
|
||||
required this.linkStyle,
|
||||
this.textColor = Colors.black,
|
||||
required this.onOpen,
|
||||
this.eventId,
|
||||
this.checkboxCheckedEvents,
|
||||
});
|
||||
|
||||
/// Keep in sync with: https://spec.matrix.org/latest/client-server-api/#mroommessage-msgtypes
|
||||
static const Set<String> allowedHtmlTags = {
|
||||
'font',
|
||||
'del',
|
||||
's',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'blockquote',
|
||||
'p',
|
||||
'a',
|
||||
'ul',
|
||||
'ol',
|
||||
'sup',
|
||||
'sub',
|
||||
'li',
|
||||
'b',
|
||||
'i',
|
||||
'u',
|
||||
'strong',
|
||||
'em',
|
||||
'strike',
|
||||
'code',
|
||||
'hr',
|
||||
'br',
|
||||
'div',
|
||||
'table',
|
||||
'thead',
|
||||
'tbody',
|
||||
'tr',
|
||||
'th',
|
||||
'td',
|
||||
'caption',
|
||||
'pre',
|
||||
'span',
|
||||
'img',
|
||||
'details',
|
||||
'summary',
|
||||
// Not in the allowlist of the matrix spec yet but should be harmless:
|
||||
'ruby',
|
||||
'rp',
|
||||
'rt',
|
||||
'html',
|
||||
'body',
|
||||
};
|
||||
|
||||
static const Set<String> ignoredHtmlTags = {'mx-reply'};
|
||||
|
||||
/// We add line breaks before these tags:
|
||||
static const Set<String> blockHtmlTags = {
|
||||
'p',
|
||||
'ul',
|
||||
'ol',
|
||||
'pre',
|
||||
'div',
|
||||
'table',
|
||||
'details',
|
||||
'blockquote',
|
||||
};
|
||||
|
||||
/// We add line breaks before these tags:
|
||||
static const Set<String> fullLineHtmlTag = {
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'li',
|
||||
};
|
||||
|
||||
/// Adding line breaks before block elements.
|
||||
List<InlineSpan> _renderWithLineBreaks(
|
||||
dom.NodeList nodes,
|
||||
BuildContext context, {
|
||||
int depth = 1,
|
||||
}) {
|
||||
final onlyElements = nodes.whereType<dom.Element>().toList();
|
||||
return [
|
||||
for (var i = 0; i < nodes.length; i++) ...[
|
||||
// Actually render the node child:
|
||||
_renderHtml(nodes[i], context, depth: depth + 1),
|
||||
// Add linebreaks between blocks:
|
||||
if (nodes[i] is dom.Element &&
|
||||
onlyElements.indexOf(nodes[i] as dom.Element) <
|
||||
onlyElements.length - 1) ...[
|
||||
if (blockHtmlTags.contains((nodes[i] as dom.Element).localName))
|
||||
const TextSpan(text: '\n\n'),
|
||||
if (fullLineHtmlTag.contains((nodes[i] as dom.Element).localName))
|
||||
const TextSpan(text: '\n'),
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
InlineSpan _renderCodeBlockNode(dom.Node node) {
|
||||
if (node is! dom.Element) {
|
||||
return TextSpan(text: node.text);
|
||||
}
|
||||
final style =
|
||||
atomOneDarkTheme[node.className.split('-').last] ??
|
||||
atomOneDarkTheme['root'];
|
||||
|
||||
return TextSpan(
|
||||
children: node.nodes.map(_renderCodeBlockNode).toList(),
|
||||
style: style,
|
||||
);
|
||||
}
|
||||
|
||||
/// Transforms a Node to an InlineSpan.
|
||||
InlineSpan _renderHtml(dom.Node node, BuildContext context, {int depth = 1}) {
|
||||
// We must not render elements nested more than 100 elements deep:
|
||||
if (depth >= 100) return const TextSpan();
|
||||
|
||||
if (node is dom.Element &&
|
||||
ignoredHtmlTags.contains(node.localName?.toLowerCase())) {
|
||||
return const TextSpan();
|
||||
}
|
||||
|
||||
// This is a text node or not permitted node, so we render it as text:
|
||||
if (node is! dom.Element || !allowedHtmlTags.contains(node.localName)) {
|
||||
var text = node.text ?? '';
|
||||
// Single linebreak nodes between Elements are ignored:
|
||||
if (text == '\n') text = '';
|
||||
|
||||
return LinkifySpan(
|
||||
text: text,
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: linkStyle,
|
||||
onOpen: onOpen,
|
||||
);
|
||||
}
|
||||
|
||||
switch (node.localName) {
|
||||
case 'br':
|
||||
return const TextSpan(text: '\n');
|
||||
case 'a':
|
||||
final href = node.attributes['href'];
|
||||
if (href == null) continue block;
|
||||
final matrixId = node.attributes['href']
|
||||
?.parseIdentifierIntoParts()
|
||||
?.primaryIdentifier;
|
||||
if (matrixId != null) {
|
||||
if (matrixId.sigil == '@') {
|
||||
final user = room.unsafeGetUserFromMemoryOrFallback(matrixId);
|
||||
return WidgetSpan(
|
||||
child: MatrixPill(
|
||||
key: Key('user_pill_$matrixId'),
|
||||
name: user.calcDisplayname(),
|
||||
avatar: user.avatarUrl,
|
||||
uri: href,
|
||||
outerContext: context,
|
||||
fontSize: fontSize,
|
||||
color: linkStyle.color,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (matrixId.sigil == '#' || matrixId.sigil == '!') {
|
||||
final room = matrixId.sigil == '!'
|
||||
? this.room.client.getRoomById(matrixId)
|
||||
: this.room.client.getRoomByAlias(matrixId);
|
||||
return WidgetSpan(
|
||||
child: MatrixPill(
|
||||
name: room?.getLocalizedDisplayname() ?? matrixId,
|
||||
avatar: room?.avatar,
|
||||
uri: href,
|
||||
outerContext: context,
|
||||
fontSize: fontSize,
|
||||
color: linkStyle.color,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return WidgetSpan(
|
||||
child: Tooltip(
|
||||
message: href,
|
||||
child: InkWell(
|
||||
splashColor: Colors.transparent,
|
||||
onTap: () => UrlLauncher(context, href, node.text).launchUrl(),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: _renderWithLineBreaks(
|
||||
node.nodes,
|
||||
context,
|
||||
depth: depth,
|
||||
),
|
||||
style: linkStyle,
|
||||
),
|
||||
style: const TextStyle(height: 1.25),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
case 'li':
|
||||
if (!{'ol', 'ul'}.contains(node.parent?.localName)) {
|
||||
continue block;
|
||||
}
|
||||
final eventId = this.eventId;
|
||||
|
||||
final isCheckbox = node.className == 'task-list-item';
|
||||
final checkboxIndex = isCheckbox
|
||||
? node.rootElement
|
||||
.getElementsByClassName('task-list-item')
|
||||
.indexOf(node) +
|
||||
1
|
||||
: null;
|
||||
final checkedByReaction = !isCheckbox
|
||||
? null
|
||||
: checkboxCheckedEvents?.firstWhereOrNull(
|
||||
(event) => event.checkedCheckboxId == checkboxIndex,
|
||||
);
|
||||
final staticallyChecked =
|
||||
isCheckbox && node.children.first.attributes['checked'] == 'true';
|
||||
|
||||
return WidgetSpan(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(left: fontSize),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
if (!isCheckbox) ...[
|
||||
if (node.parent?.localName == 'ul')
|
||||
const TextSpan(text: '• '),
|
||||
if (node.parent?.localName == 'ol')
|
||||
TextSpan(
|
||||
text:
|
||||
'${(node.parent?.nodes.whereType<dom.Element>().toList().indexOf(node) ?? 0) + (int.tryParse(node.parent?.attributes['start'] ?? '1') ?? 1)}. ',
|
||||
),
|
||||
],
|
||||
if (node.className == 'task-list-item')
|
||||
WidgetSpan(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: SizedBox.square(
|
||||
dimension: fontSize + 2,
|
||||
child: CupertinoCheckbox(
|
||||
checkColor: textColor,
|
||||
side: BorderSide(color: textColor),
|
||||
activeColor: textColor.withAlpha(64),
|
||||
value:
|
||||
staticallyChecked || checkedByReaction != null,
|
||||
onChanged:
|
||||
eventId == null ||
|
||||
checkboxIndex == null ||
|
||||
staticallyChecked ||
|
||||
!room.canSendDefaultMessages ||
|
||||
(checkedByReaction != null &&
|
||||
checkedByReaction.senderId !=
|
||||
room.client.userID)
|
||||
? null
|
||||
: (_) => showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => checkedByReaction != null
|
||||
? room.redactEvent(
|
||||
checkedByReaction.eventId,
|
||||
)
|
||||
: room.checkCheckbox(
|
||||
eventId,
|
||||
checkboxIndex,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
..._renderWithLineBreaks(node.nodes, context, depth: depth),
|
||||
],
|
||||
style: TextStyle(fontSize: fontSize, color: textColor),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
case 'blockquote':
|
||||
return WidgetSpan(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.only(left: 8.0),
|
||||
decoration: BoxDecoration(
|
||||
border: Border(left: BorderSide(color: textColor, width: 5)),
|
||||
),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: _renderWithLineBreaks(
|
||||
node.nodes,
|
||||
context,
|
||||
depth: depth,
|
||||
),
|
||||
),
|
||||
style: TextStyle(
|
||||
fontStyle: FontStyle.italic,
|
||||
fontSize: fontSize,
|
||||
color: textColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
case 'code':
|
||||
final isInline = node.parent?.localName != 'pre';
|
||||
final lang =
|
||||
node.className
|
||||
.split(' ')
|
||||
.singleWhereOrNull(
|
||||
(className) => className.startsWith('language-'),
|
||||
)
|
||||
?.split('language-')
|
||||
.last ??
|
||||
'md';
|
||||
final highlightedHtml = highlight
|
||||
.parse(node.text, language: lang)
|
||||
.toHtml();
|
||||
final element = parser.parse(highlightedHtml).body;
|
||||
if (element == null) {
|
||||
return const TextSpan(text: 'Unable to render code block!');
|
||||
}
|
||||
|
||||
return WidgetSpan(
|
||||
child: Material(
|
||||
color: atomOneBackgroundColor,
|
||||
shape: RoundedRectangleBorder(
|
||||
side: const BorderSide(color: hightlightTextColor),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Padding(
|
||||
padding: isInline
|
||||
? const EdgeInsets.symmetric(horizontal: 4.0)
|
||||
: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
|
||||
child: Text.rich(
|
||||
TextSpan(children: [_renderCodeBlockNode(element)]),
|
||||
selectionColor: hightlightTextColor.withAlpha(128),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
case 'img':
|
||||
final mxcUrl = Uri.tryParse(node.attributes['src'] ?? '');
|
||||
if (mxcUrl == null || mxcUrl.scheme != 'mxc') {
|
||||
return TextSpan(text: node.attributes['alt']);
|
||||
}
|
||||
|
||||
final width = double.tryParse(node.attributes['width'] ?? '');
|
||||
final height = double.tryParse(node.attributes['height'] ?? '');
|
||||
const defaultDimension = 64.0;
|
||||
final actualWidth = width ?? height ?? defaultDimension;
|
||||
final actualHeight = height ?? width ?? defaultDimension;
|
||||
|
||||
return WidgetSpan(
|
||||
child: SizedBox(
|
||||
width: actualWidth,
|
||||
height: actualHeight,
|
||||
child: MxcImage(
|
||||
uri: mxcUrl,
|
||||
width: actualWidth,
|
||||
height: actualHeight,
|
||||
isThumbnail: (actualWidth * actualHeight) > (256 * 256),
|
||||
),
|
||||
),
|
||||
);
|
||||
case 'table':
|
||||
return WidgetSpan(
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Table(
|
||||
defaultColumnWidth: const IntrinsicColumnWidth(),
|
||||
border: TableBorder.all(color: textColor.withAlpha(100)),
|
||||
children: node.nodes
|
||||
.whereType<dom.Element>()
|
||||
.expand(
|
||||
(e) =>
|
||||
e.localName == 'thead' ||
|
||||
e.localName == 'tbody' ||
|
||||
e.localName == 'tfoot'
|
||||
? e.nodes.whereType<dom.Element>()
|
||||
: [e],
|
||||
)
|
||||
.where((e) => e.localName == 'tr')
|
||||
.map(
|
||||
(tr) => TableRow(
|
||||
children: tr.nodes
|
||||
.whereType<dom.Element>()
|
||||
.where(
|
||||
(e) => e.localName == 'td' || e.localName == 'th',
|
||||
)
|
||||
.map(
|
||||
(cell) => Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
vertical: 3,
|
||||
),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: _renderWithLineBreaks(
|
||||
cell.nodes,
|
||||
context,
|
||||
depth: depth,
|
||||
),
|
||||
style: cell.localName == 'th'
|
||||
? const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: fontSize,
|
||||
color: textColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
);
|
||||
case 'thead':
|
||||
case 'tbody':
|
||||
case 'tfoot':
|
||||
case 'tr':
|
||||
case 'th':
|
||||
case 'td':
|
||||
case 'caption':
|
||||
// These are handled by the 'table' case above; if encountered
|
||||
// outside a table, render children inline as fallback.
|
||||
return TextSpan(
|
||||
children: _renderWithLineBreaks(node.nodes, context, depth: depth),
|
||||
);
|
||||
case 'hr':
|
||||
return const WidgetSpan(child: Divider());
|
||||
case 'details':
|
||||
var obscure = true;
|
||||
return WidgetSpan(
|
||||
child: StatefulBuilder(
|
||||
builder: (context, setState) => InkWell(
|
||||
splashColor: Colors.transparent,
|
||||
onTap: () => setState(() {
|
||||
obscure = !obscure;
|
||||
}),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
WidgetSpan(
|
||||
child: Icon(
|
||||
obscure ? Icons.arrow_right : Icons.arrow_drop_down,
|
||||
size: fontSize * 1.2,
|
||||
color: textColor,
|
||||
),
|
||||
),
|
||||
if (obscure)
|
||||
...node.nodes
|
||||
.where(
|
||||
(node) =>
|
||||
node is dom.Element &&
|
||||
node.localName == 'summary',
|
||||
)
|
||||
.map(
|
||||
(node) => _renderHtml(node, context, depth: depth),
|
||||
)
|
||||
else
|
||||
..._renderWithLineBreaks(
|
||||
node.nodes,
|
||||
context,
|
||||
depth: depth,
|
||||
),
|
||||
],
|
||||
),
|
||||
style: TextStyle(fontSize: fontSize, color: textColor),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
case 'span':
|
||||
if (!node.attributes.containsKey('data-mx-spoiler')) {
|
||||
continue block;
|
||||
}
|
||||
var obscure = true;
|
||||
return WidgetSpan(
|
||||
child: StatefulBuilder(
|
||||
builder: (context, setState) => InkWell(
|
||||
splashColor: Colors.transparent,
|
||||
onTap: () => setState(() {
|
||||
obscure = !obscure;
|
||||
}),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: _renderWithLineBreaks(
|
||||
node.nodes,
|
||||
context,
|
||||
depth: depth,
|
||||
),
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: fontSize,
|
||||
color: textColor,
|
||||
backgroundColor: obscure ? textColor : null,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
block:
|
||||
default:
|
||||
return TextSpan(
|
||||
style: switch (node.localName) {
|
||||
'body' => TextStyle(fontSize: fontSize, color: textColor),
|
||||
'a' => linkStyle,
|
||||
'strong' => const TextStyle(fontWeight: FontWeight.bold),
|
||||
'em' || 'i' => const TextStyle(fontStyle: FontStyle.italic),
|
||||
'del' || 's' || 'strikethrough' => const TextStyle(
|
||||
decoration: TextDecoration.lineThrough,
|
||||
),
|
||||
'u' => const TextStyle(decoration: TextDecoration.underline),
|
||||
'h1' => TextStyle(fontSize: fontSize * 1.6, height: 2),
|
||||
'h2' => TextStyle(fontSize: fontSize * 1.5, height: 2),
|
||||
'h3' => TextStyle(fontSize: fontSize * 1.4, height: 2),
|
||||
'h4' => TextStyle(fontSize: fontSize * 1.3, height: 1.75),
|
||||
'h5' => TextStyle(fontSize: fontSize * 1.2, height: 1.75),
|
||||
'h6' => TextStyle(fontSize: fontSize * 1.1, height: 1.5),
|
||||
'span' => TextStyle(
|
||||
color:
|
||||
node.attributes['color']?.hexToColor ??
|
||||
node.attributes['data-mx-color']?.hexToColor ??
|
||||
textColor,
|
||||
backgroundColor: node.attributes['data-mx-bg-color']?.hexToColor,
|
||||
),
|
||||
'sup' => const TextStyle(
|
||||
fontFeatures: [FontFeature.superscripts()],
|
||||
),
|
||||
'sub' => const TextStyle(fontFeatures: [FontFeature.subscripts()]),
|
||||
_ => null,
|
||||
},
|
||||
children: _renderWithLineBreaks(node.nodes, context, depth: depth),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final element = parser.parse(html).body ?? dom.Element.html('');
|
||||
final configuredMaxLines = AppSettings.messagePreviewMaxLines.value;
|
||||
final maxLines = configuredMaxLines <= 0 ? null : configuredMaxLines;
|
||||
final span = _renderHtml(element, context);
|
||||
final style = TextStyle(fontSize: fontSize, color: textColor);
|
||||
|
||||
if (maxLines == null) {
|
||||
return Text.rich(
|
||||
span,
|
||||
style: style,
|
||||
selectionColor: textColor.withAlpha(128),
|
||||
);
|
||||
}
|
||||
|
||||
// Heuristic: if plain text has enough newlines or length, it will overflow.
|
||||
final plainText = element.text;
|
||||
final lineCount = '\n'.allMatches(plainText).length + 1;
|
||||
final likelyOverflows =
|
||||
lineCount > maxLines || plainText.length > maxLines * 50;
|
||||
|
||||
if (!likelyOverflows) {
|
||||
return Text.rich(
|
||||
span,
|
||||
style: style,
|
||||
selectionColor: textColor.withAlpha(128),
|
||||
);
|
||||
}
|
||||
|
||||
return _CollapsibleText(
|
||||
span: span,
|
||||
style: style,
|
||||
maxLines: maxLines,
|
||||
textColor: textColor,
|
||||
linkColor: linkStyle.color ?? textColor,
|
||||
fontSize: fontSize,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CollapsibleText extends StatefulWidget {
|
||||
final InlineSpan span;
|
||||
final TextStyle style;
|
||||
final int maxLines;
|
||||
final Color textColor;
|
||||
final Color linkColor;
|
||||
final double fontSize;
|
||||
|
||||
const _CollapsibleText({
|
||||
required this.span,
|
||||
required this.style,
|
||||
required this.maxLines,
|
||||
required this.textColor,
|
||||
required this.linkColor,
|
||||
required this.fontSize,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_CollapsibleText> createState() => _CollapsibleTextState();
|
||||
}
|
||||
|
||||
class _CollapsibleTextState extends State<_CollapsibleText> {
|
||||
bool _expanded = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = L10n.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
AnimatedSize(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
alignment: Alignment.topLeft,
|
||||
child: Text.rich(
|
||||
widget.span,
|
||||
style: widget.style,
|
||||
maxLines: _expanded ? null : widget.maxLines,
|
||||
overflow: _expanded ? TextOverflow.visible : TextOverflow.ellipsis,
|
||||
selectionColor: widget.textColor.withAlpha(128),
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: TextButton.icon(
|
||||
onPressed: () => setState(() => _expanded = !_expanded),
|
||||
style: TextButton.styleFrom(foregroundColor: widget.linkColor),
|
||||
icon: Icon(_expanded ? Icons.arrow_drop_up : Icons.arrow_drop_down),
|
||||
label: Text(_expanded ? l10n.showLess : l10n.showMore),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MatrixPill extends StatelessWidget {
|
||||
final String name;
|
||||
final BuildContext outerContext;
|
||||
final Uri? avatar;
|
||||
final String uri;
|
||||
final double? fontSize;
|
||||
final Color? color;
|
||||
|
||||
const MatrixPill({
|
||||
super.key,
|
||||
required this.name,
|
||||
required this.outerContext,
|
||||
this.avatar,
|
||||
required this.uri,
|
||||
required this.fontSize,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InkWell(
|
||||
splashColor: Colors.transparent,
|
||||
onTap: UrlLauncher(outerContext, uri).launchUrl,
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
WidgetSpan(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 4.0),
|
||||
child: Avatar(mxContent: avatar, name: name, size: 16),
|
||||
),
|
||||
),
|
||||
TextSpan(
|
||||
text: name,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
decorationColor: color,
|
||||
decoration: TextDecoration.underline,
|
||||
fontSize: fontSize,
|
||||
height: 1.25,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension on String {
|
||||
Color? get hexToColor {
|
||||
var hexCode = this;
|
||||
if (hexCode.startsWith('#')) hexCode = hexCode.substring(1);
|
||||
if (hexCode.length == 6) hexCode = 'FF$hexCode';
|
||||
final colorValue = int.tryParse(hexCode, radix: 16);
|
||||
return colorValue == null ? null : Color(colorValue);
|
||||
}
|
||||
}
|
||||
|
||||
extension on dom.Element {
|
||||
dom.Element get rootElement => parent?.rootElement ?? this;
|
||||
}
|
||||
175
lib/pages/chat/events/image_bubble.dart
Normal file
175
lib/pages/chat/events/image_bubble.dart
Normal file
@@ -0,0 +1,175 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/utils/file_description.dart';
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../../widgets/blur_hash.dart';
|
||||
|
||||
class ImageBubble extends StatelessWidget {
|
||||
final Event event;
|
||||
final bool tapToView;
|
||||
final BoxFit fit;
|
||||
final Color? backgroundColor;
|
||||
final Color? textColor;
|
||||
final Color? linkColor;
|
||||
final bool thumbnailOnly;
|
||||
final bool animated;
|
||||
final double width;
|
||||
final double height;
|
||||
final void Function()? onTap;
|
||||
final BorderRadius? borderRadius;
|
||||
final Timeline? timeline;
|
||||
|
||||
const ImageBubble(
|
||||
this.event, {
|
||||
this.tapToView = true,
|
||||
this.backgroundColor,
|
||||
this.fit = BoxFit.contain,
|
||||
this.thumbnailOnly = true,
|
||||
this.width = 400,
|
||||
this.height = 300,
|
||||
this.animated = false,
|
||||
this.onTap,
|
||||
this.borderRadius,
|
||||
this.timeline,
|
||||
this.textColor,
|
||||
this.linkColor,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
var borderRadius =
|
||||
this.borderRadius ?? BorderRadius.circular(AppConfig.borderRadius);
|
||||
|
||||
final fileDescription = event.fileDescription;
|
||||
final textColor = this.textColor;
|
||||
|
||||
if (fileDescription != null) {
|
||||
borderRadius = borderRadius.copyWith(
|
||||
bottomLeft: Radius.zero,
|
||||
bottomRight: Radius.zero,
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
spacing: 8,
|
||||
children: [
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: borderRadius,
|
||||
side: BorderSide(
|
||||
color: event.messageType == MessageTypes.Sticker
|
||||
? Colors.transparent
|
||||
: theme.dividerColor,
|
||||
),
|
||||
),
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: borderRadius,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
Hero(
|
||||
tag: event.eventId,
|
||||
child: AppSettings.showThumbnailsInTimeline.value
|
||||
? MxcImage(
|
||||
cacheKey: event.transactionId ?? event.eventId,
|
||||
cacheName: event.room.id,
|
||||
event: event,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
animated: animated,
|
||||
isThumbnail: thumbnailOnly,
|
||||
placeholder: event.messageType == MessageTypes.Sticker
|
||||
? null
|
||||
: (_) => _ImageBubblePlaceholder(
|
||||
event: event,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
),
|
||||
)
|
||||
: _ImageBubblePlaceholder(
|
||||
event: event,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (fileDescription != null && textColor != null)
|
||||
SizedBox(
|
||||
width: width,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Linkify(
|
||||
text: fileDescription,
|
||||
textScaleFactor: MediaQuery.textScalerOf(context).scale(1),
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: linkColor,
|
||||
),
|
||||
onOpen: (url) => UrlLauncher(context, url.url).launchUrl(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ImageBubblePlaceholder extends StatelessWidget {
|
||||
final Event event;
|
||||
final double width, height;
|
||||
final BoxFit fit;
|
||||
|
||||
const _ImageBubblePlaceholder({
|
||||
required this.event,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.fit,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final blurHashString =
|
||||
event.infoMap.tryGet<String>('xyz.amorgan.blurhash') ??
|
||||
'LEHV6nWB2yk8pyo0adR*.7kCMdnj';
|
||||
return SizedBox(
|
||||
width: width,
|
||||
height: height,
|
||||
child: BlurHash(
|
||||
blurhash: blurHashString,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
105
lib/pages/chat/events/map_bubble.dart
Normal file
105
lib/pages/chat/events/map_bubble.dart
Normal file
@@ -0,0 +1,105 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:flutter_map/flutter_map.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
import '../../../config/app_config.dart';
|
||||
|
||||
class MapBubble extends StatelessWidget {
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
final double zoom;
|
||||
final double width;
|
||||
final double height;
|
||||
final double radius;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
const MapBubble({
|
||||
required this.latitude,
|
||||
required this.longitude,
|
||||
this.zoom = 14.0,
|
||||
this.width = 400,
|
||||
this.height = 400,
|
||||
this.radius = 10.0,
|
||||
this.onTap,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Container(
|
||||
constraints: BoxConstraints.loose(Size(width, height)),
|
||||
child: AspectRatio(
|
||||
aspectRatio: width / height,
|
||||
child: Stack(
|
||||
children: <Widget>[
|
||||
FlutterMap(
|
||||
options: MapOptions(
|
||||
initialCenter: LatLng(latitude, longitude),
|
||||
initialZoom: zoom,
|
||||
),
|
||||
children: [
|
||||
TileLayer(
|
||||
maxZoom: 20,
|
||||
minZoom: 0,
|
||||
urlTemplate:
|
||||
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
userAgentPackageName: AppConfig.appId,
|
||||
subdomains: const ['a', 'b', 'c'],
|
||||
),
|
||||
MarkerLayer(
|
||||
rotate: true,
|
||||
markers: [
|
||||
Marker(
|
||||
point: LatLng(latitude, longitude),
|
||||
width: 30,
|
||||
height: 30,
|
||||
child: Transform.translate(
|
||||
// No idea why the offset has to be like this, instead of -15
|
||||
// It has been determined by trying out, though, that this yields
|
||||
// the tip of the location pin to be static when zooming.
|
||||
// Might have to do with psychological perception of where the tip exactly is
|
||||
offset: const Offset(0, -12.5),
|
||||
child: const Icon(
|
||||
Icons.location_pin,
|
||||
color: Colors.red,
|
||||
size: 30,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
Container(
|
||||
alignment: Alignment.bottomRight,
|
||||
child: Text(
|
||||
' © OpenStreetMap contributors ',
|
||||
style: TextStyle(
|
||||
color: theme.brightness == Brightness.dark
|
||||
? Colors.white
|
||||
: Colors.black,
|
||||
backgroundColor: theme.appBarTheme.backgroundColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
child: Tooltip(
|
||||
message: L10n.of(context).openInMaps,
|
||||
child: InkWell(onTap: onTap, child: SizedBox.expand()),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
1037
lib/pages/chat/events/message.dart
Normal file
1037
lib/pages/chat/events/message.dart
Normal file
File diff suppressed because it is too large
Load Diff
321
lib/pages/chat/events/message_content.dart
Normal file
321
lib/pages/chat/events/message_content.dart
Normal file
@@ -0,0 +1,321 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/events/poll.dart';
|
||||
import 'package:tatchat/pages/chat/events/video_player.dart';
|
||||
import 'package:tatchat/pages/image_viewer/image_viewer.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../../config/app_config.dart';
|
||||
import '../../../utils/event_checkbox_extension.dart';
|
||||
import '../../../utils/platform_infos.dart';
|
||||
import '../../../utils/url_launcher.dart';
|
||||
import 'audio_player.dart';
|
||||
import 'cute_events.dart';
|
||||
import 'html_message.dart';
|
||||
import 'image_bubble.dart';
|
||||
import 'map_bubble.dart';
|
||||
import 'message_download_content.dart';
|
||||
|
||||
class MessageContent extends StatelessWidget {
|
||||
final Event event;
|
||||
final Color textColor;
|
||||
final Color linkColor;
|
||||
final void Function(Event)? onInfoTab;
|
||||
final BorderRadius borderRadius;
|
||||
final Timeline timeline;
|
||||
final bool selected;
|
||||
final Set<String> bigEmojis;
|
||||
|
||||
const MessageContent(
|
||||
this.event, {
|
||||
this.onInfoTab,
|
||||
super.key,
|
||||
required this.timeline,
|
||||
required this.textColor,
|
||||
required this.linkColor,
|
||||
required this.borderRadius,
|
||||
required this.selected,
|
||||
required this.bigEmojis,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const fontSize = AppConfig.messageFontSize;
|
||||
final buttonTextColor = textColor;
|
||||
switch (event.type) {
|
||||
case EventTypes.Message:
|
||||
case EventTypes.Encrypted:
|
||||
case EventTypes.Sticker:
|
||||
switch (event.messageType) {
|
||||
case MessageTypes.Image:
|
||||
case MessageTypes.Sticker:
|
||||
if (event.redacted) continue textmessage;
|
||||
final maxSize = event.messageType == MessageTypes.Sticker
|
||||
? 128.0
|
||||
: 256.0;
|
||||
final w = event.content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<int>('w');
|
||||
final h = event.content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<int>('h');
|
||||
var width = maxSize;
|
||||
var height = maxSize;
|
||||
var fit = event.messageType == MessageTypes.Sticker
|
||||
? BoxFit.contain
|
||||
: BoxFit.cover;
|
||||
if (w != null && h != null) {
|
||||
fit = BoxFit.contain;
|
||||
if (w > h) {
|
||||
width = maxSize;
|
||||
height = max(32, maxSize * (h / w));
|
||||
} else {
|
||||
height = maxSize;
|
||||
width = max(32, maxSize * (w / h));
|
||||
}
|
||||
}
|
||||
return ImageBubble(
|
||||
event,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: fit,
|
||||
borderRadius: borderRadius,
|
||||
timeline: timeline,
|
||||
textColor: textColor,
|
||||
onTap: () => showDialog(
|
||||
context: context,
|
||||
builder: (_) => ImageViewer(
|
||||
event,
|
||||
timeline: timeline,
|
||||
outerContext: context,
|
||||
),
|
||||
),
|
||||
);
|
||||
case CuteEventContent.eventType:
|
||||
return CuteContent(event);
|
||||
case MessageTypes.Audio:
|
||||
if (PlatformInfos.isMobile ||
|
||||
PlatformInfos.isMacOS ||
|
||||
PlatformInfos.isWeb ||
|
||||
PlatformInfos.isLinux) {
|
||||
return AudioPlayerWidget(
|
||||
event,
|
||||
color: textColor,
|
||||
linkColor: linkColor,
|
||||
fontSize: fontSize,
|
||||
);
|
||||
}
|
||||
return MessageDownloadContent(
|
||||
event,
|
||||
textColor: textColor,
|
||||
linkColor: linkColor,
|
||||
);
|
||||
case MessageTypes.Video:
|
||||
return EventVideoPlayer(
|
||||
event,
|
||||
textColor: textColor,
|
||||
linkColor: linkColor,
|
||||
timeline: timeline,
|
||||
);
|
||||
case MessageTypes.File:
|
||||
return MessageDownloadContent(
|
||||
event,
|
||||
textColor: textColor,
|
||||
linkColor: linkColor,
|
||||
);
|
||||
case MessageTypes.Location:
|
||||
final geoUri = Uri.tryParse(
|
||||
event.content.tryGet<String>('geo_uri')!,
|
||||
);
|
||||
if (geoUri != null && geoUri.scheme == 'geo') {
|
||||
final latlong = geoUri.path
|
||||
.split(';')
|
||||
.first
|
||||
.split(',')
|
||||
.map(double.tryParse)
|
||||
.toList();
|
||||
if (latlong.length == 2 &&
|
||||
latlong.first != null &&
|
||||
latlong.last != null) {
|
||||
return MapBubble(
|
||||
onTap: () =>
|
||||
UrlLauncher(context, geoUri.toString()).launchUrl(),
|
||||
latitude: latlong.first!,
|
||||
longitude: latlong.last!,
|
||||
);
|
||||
}
|
||||
}
|
||||
continue textmessage;
|
||||
case MessageTypes.Text:
|
||||
case MessageTypes.Notice:
|
||||
case MessageTypes.Emote:
|
||||
case MessageTypes.None:
|
||||
textmessage:
|
||||
default:
|
||||
if (event.redacted) {
|
||||
return RedactionWidget(
|
||||
event: event,
|
||||
buttonTextColor: buttonTextColor,
|
||||
onInfoTab: onInfoTab,
|
||||
fontSize: fontSize,
|
||||
);
|
||||
}
|
||||
var html = AppSettings.renderHtml.value && event.isRichMessage
|
||||
? event.formattedText
|
||||
: event.body.replaceAll('<', '<').replaceAll('>', '>');
|
||||
if (event.messageType == MessageTypes.Emote) {
|
||||
html = '* $html';
|
||||
}
|
||||
|
||||
final bigEmotes =
|
||||
!event.isRichMessage && bigEmojis.contains(event.body);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: HtmlMessage(
|
||||
html: html,
|
||||
textColor: textColor,
|
||||
room: event.room,
|
||||
fontSize: AppConfig.messageFontSize * (bigEmotes ? 5 : 1),
|
||||
linkStyle: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: linkColor,
|
||||
),
|
||||
onOpen: (url) => UrlLauncher(context, url.url).launchUrl(),
|
||||
eventId: event.eventId,
|
||||
checkboxCheckedEvents: event.aggregatedEvents(
|
||||
timeline,
|
||||
EventCheckboxRoomExtension.relationshipType,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
case PollEventContent.startType:
|
||||
if (event.redacted) {
|
||||
return RedactionWidget(
|
||||
event: event,
|
||||
buttonTextColor: buttonTextColor,
|
||||
onInfoTab: onInfoTab,
|
||||
fontSize: fontSize,
|
||||
);
|
||||
}
|
||||
return PollWidget(
|
||||
event: event,
|
||||
timeline: timeline,
|
||||
textColor: textColor,
|
||||
linkColor: linkColor,
|
||||
);
|
||||
case EventTypes.CallInvite:
|
||||
return FutureBuilder<User?>(
|
||||
future: event.fetchSenderUser(),
|
||||
builder: (context, snapshot) {
|
||||
return _ButtonContent(
|
||||
label: L10n.of(context).startedACall(
|
||||
snapshot.data?.calcDisplayname() ??
|
||||
event.senderFromMemoryOrFallback.calcDisplayname(),
|
||||
),
|
||||
icon: '📞',
|
||||
textColor: buttonTextColor,
|
||||
onPressed: () => onInfoTab!(event),
|
||||
fontSize: fontSize,
|
||||
);
|
||||
},
|
||||
);
|
||||
default:
|
||||
return FutureBuilder<User?>(
|
||||
future: event.fetchSenderUser(),
|
||||
builder: (context, snapshot) {
|
||||
return _ButtonContent(
|
||||
label: L10n.of(context).userSentUnknownEvent(
|
||||
snapshot.data?.calcDisplayname() ??
|
||||
event.senderFromMemoryOrFallback.calcDisplayname(),
|
||||
event.type,
|
||||
),
|
||||
icon: 'ℹ️',
|
||||
textColor: buttonTextColor,
|
||||
onPressed: () => onInfoTab!(event),
|
||||
fontSize: fontSize,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class RedactionWidget extends StatelessWidget {
|
||||
const RedactionWidget({
|
||||
super.key,
|
||||
required this.event,
|
||||
required this.buttonTextColor,
|
||||
required this.onInfoTab,
|
||||
required this.fontSize,
|
||||
});
|
||||
|
||||
final Event event;
|
||||
final Color buttonTextColor;
|
||||
final void Function(Event p1)? onInfoTab;
|
||||
final double fontSize;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FutureBuilder<User?>(
|
||||
future: event.redactedBecause?.fetchSenderUser(),
|
||||
builder: (context, snapshot) {
|
||||
final reason = event.redactedBecause?.content.tryGet<String>('reason');
|
||||
final redactedBy =
|
||||
snapshot.data?.calcDisplayname() ??
|
||||
event.redactedBecause?.senderId.localpart ??
|
||||
L10n.of(context).user;
|
||||
return _ButtonContent(
|
||||
label: reason == null
|
||||
? L10n.of(context).redactedBy(redactedBy)
|
||||
: L10n.of(context).redactedByBecause(redactedBy, reason),
|
||||
icon: '🗑️',
|
||||
textColor: buttonTextColor.withAlpha(128),
|
||||
onPressed: () => onInfoTab!(event),
|
||||
fontSize: fontSize,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ButtonContent extends StatelessWidget {
|
||||
final void Function() onPressed;
|
||||
final String label;
|
||||
final String icon;
|
||||
final Color? textColor;
|
||||
final double fontSize;
|
||||
|
||||
const _ButtonContent({
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.textColor,
|
||||
required this.onPressed,
|
||||
required this.fontSize,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: InkWell(
|
||||
onTap: onPressed,
|
||||
child: Text(
|
||||
'$icon $label',
|
||||
style: TextStyle(color: textColor, fontSize: fontSize),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
124
lib/pages/chat/events/message_download_content.dart
Normal file
124
lib/pages/chat/events/message_download_content.dart
Normal file
@@ -0,0 +1,124 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/pages/chat/events/file_send_status_indicator.dart';
|
||||
import 'package:tatchat/utils/file_description.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/event_extension.dart';
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class MessageDownloadContent extends StatelessWidget {
|
||||
final Event event;
|
||||
final Color textColor;
|
||||
final Color linkColor;
|
||||
|
||||
const MessageDownloadContent(
|
||||
this.event, {
|
||||
required this.textColor,
|
||||
required this.linkColor,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final filename = event.content.tryGet<String>('filename') ?? event.body;
|
||||
final filetype = (filename.contains('.')
|
||||
? filename.split('.').last.toUpperCase()
|
||||
: event.content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<String>('mimetype')
|
||||
?.toUpperCase() ??
|
||||
'UNKNOWN');
|
||||
final sizeString = event.sizeString ?? '?MB';
|
||||
final fileDescription = event.fileDescription;
|
||||
final fileSendingStatus = event.fileSendingStatus;
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
crossAxisAlignment: .start,
|
||||
spacing: 8,
|
||||
children: [
|
||||
Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius / 2),
|
||||
onTap: () => event.saveFile(context),
|
||||
child: Container(
|
||||
width: 400,
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 16,
|
||||
children: [
|
||||
if (fileSendingStatus != null)
|
||||
FileSendStatusIndicator(
|
||||
fileSendingStatus: fileSendingStatus,
|
||||
)
|
||||
else
|
||||
CircleAvatar(
|
||||
backgroundColor: textColor.withAlpha(32),
|
||||
child: Icon(
|
||||
Icons.file_download_outlined,
|
||||
color: textColor,
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: Column(
|
||||
crossAxisAlignment: .start,
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Text(
|
||||
filename,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'$sizeString | $filetype',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(color: textColor, fontSize: 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (fileDescription != null) ...[
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 8.0,
|
||||
),
|
||||
child: Linkify(
|
||||
text: fileDescription,
|
||||
textScaleFactor: MediaQuery.textScalerOf(context).scale(1),
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: linkColor,
|
||||
),
|
||||
onOpen: (url) => UrlLauncher(context, url.url).launchUrl(),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
208
lib/pages/chat/events/message_reactions.dart
Normal file
208
lib/pages/chat/events/message_reactions.dart
Normal file
@@ -0,0 +1,208 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart' show IterableExtension;
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class MessageReactions extends StatelessWidget {
|
||||
final Event event;
|
||||
final Timeline timeline;
|
||||
|
||||
const MessageReactions(this.event, this.timeline, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final allReactionEvents = event.aggregatedEvents(
|
||||
timeline,
|
||||
RelationshipTypes.reaction,
|
||||
);
|
||||
final reactionMap = <String, _ReactionEntry>{};
|
||||
final client = Matrix.of(context).client;
|
||||
|
||||
for (final e in allReactionEvents) {
|
||||
final key = e.content
|
||||
.tryGetMap<String, Object?>('m.relates_to')
|
||||
?.tryGet<String>('key');
|
||||
if (key != null) {
|
||||
if (!reactionMap.containsKey(key)) {
|
||||
reactionMap[key] = _ReactionEntry(
|
||||
key: key,
|
||||
count: 0,
|
||||
reacted: false,
|
||||
reactors: [],
|
||||
);
|
||||
}
|
||||
reactionMap[key]!.count++;
|
||||
reactionMap[key]!.reactors!.add(e.senderFromMemoryOrFallback);
|
||||
reactionMap[key]!.reacted |= e.senderId == e.room.client.userID;
|
||||
}
|
||||
}
|
||||
|
||||
final reactionList = reactionMap.values.toList();
|
||||
reactionList.sort((a, b) => b.count - a.count > 0 ? 1 : -1);
|
||||
final ownMessage = event.senderId == event.room.client.userID;
|
||||
return Wrap(
|
||||
spacing: 4.0,
|
||||
runSpacing: 4.0,
|
||||
alignment: ownMessage ? WrapAlignment.end : WrapAlignment.start,
|
||||
children: [
|
||||
...reactionList.map(
|
||||
(r) => _Reaction(
|
||||
reactionKey: r.key,
|
||||
count: r.count,
|
||||
reacted: r.reacted,
|
||||
onTap: () {
|
||||
if (r.reacted) {
|
||||
final evt = allReactionEvents.firstWhereOrNull(
|
||||
(e) =>
|
||||
e.senderId == e.room.client.userID &&
|
||||
e.content.tryGetMap('m.relates_to')?['key'] == r.key,
|
||||
);
|
||||
if (evt != null) {
|
||||
showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: evt.redactEvent,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
event.room.sendReaction(event.eventId, r.key);
|
||||
}
|
||||
},
|
||||
onLongPress: () async => await _AdaptableReactorsDialog(
|
||||
client: client,
|
||||
reactionEntry: r,
|
||||
).show(context),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Reaction extends StatelessWidget {
|
||||
final String reactionKey;
|
||||
final int count;
|
||||
final bool? reacted;
|
||||
final void Function()? onTap;
|
||||
final void Function()? onLongPress;
|
||||
|
||||
const _Reaction({
|
||||
required this.reactionKey,
|
||||
required this.count,
|
||||
required this.reacted,
|
||||
required this.onTap,
|
||||
required this.onLongPress,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
Widget content;
|
||||
if (reactionKey.startsWith('mxc://')) {
|
||||
content = MxcImage(
|
||||
uri: Uri.parse(reactionKey),
|
||||
width: 20,
|
||||
height: 20,
|
||||
animated: false,
|
||||
isThumbnail: false,
|
||||
);
|
||||
} else {
|
||||
var renderKey = Characters(reactionKey);
|
||||
if (renderKey.length > 10) {
|
||||
renderKey = renderKey.getRange(0, 9) + Characters('…');
|
||||
}
|
||||
content = Text(renderKey.toString(), style: TextStyle(fontSize: 14));
|
||||
}
|
||||
return Badge(
|
||||
isLabelVisible: count > 1,
|
||||
label: Text(count.toString()),
|
||||
textStyle: TextStyle(fontSize: 10),
|
||||
textColor: theme.colorScheme.onPrimary,
|
||||
backgroundColor: theme.colorScheme.primary.withAlpha(200),
|
||||
child: InkWell(
|
||||
onTap: () => onTap != null ? onTap!() : null,
|
||||
onLongPress: () => onLongPress != null ? onLongPress!() : null,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius / 2),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.secondaryContainer,
|
||||
border: Border.all(
|
||||
color: reacted == true
|
||||
? theme.colorScheme.secondary
|
||||
: theme.colorScheme.secondaryContainer,
|
||||
width: 1,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius / 2),
|
||||
),
|
||||
height: 24,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 3),
|
||||
child: content,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ReactionEntry {
|
||||
String key;
|
||||
int count;
|
||||
bool reacted;
|
||||
List<User>? reactors;
|
||||
|
||||
_ReactionEntry({
|
||||
required this.key,
|
||||
required this.count,
|
||||
required this.reacted,
|
||||
this.reactors,
|
||||
});
|
||||
}
|
||||
|
||||
class _AdaptableReactorsDialog extends StatelessWidget {
|
||||
final Client? client;
|
||||
final _ReactionEntry? reactionEntry;
|
||||
|
||||
const _AdaptableReactorsDialog({this.client, this.reactionEntry});
|
||||
|
||||
Future<bool?> show(BuildContext context) => showDialog(
|
||||
context: context,
|
||||
builder: (context) => this,
|
||||
barrierDismissible: true,
|
||||
useRootNavigator: false,
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final body = SingleChildScrollView(
|
||||
child: Wrap(
|
||||
spacing: 8.0,
|
||||
runSpacing: 4.0,
|
||||
alignment: WrapAlignment.center,
|
||||
children: <Widget>[
|
||||
for (final reactor in reactionEntry!.reactors!)
|
||||
Chip(
|
||||
avatar: Avatar(
|
||||
mxContent: reactor.avatarUrl,
|
||||
name: reactor.displayName,
|
||||
client: client,
|
||||
presenceUserId: reactor.stateKey,
|
||||
),
|
||||
label: Text(reactor.displayName!),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
final title = Center(child: Text(reactionEntry!.key));
|
||||
|
||||
return AlertDialog(title: title, content: body);
|
||||
}
|
||||
}
|
||||
224
lib/pages/chat/events/poll.dart
Normal file
224
lib/pages/chat/events/poll.dart
Normal file
@@ -0,0 +1,224 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:async/async.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart' hide Result;
|
||||
|
||||
class PollWidget extends StatelessWidget {
|
||||
final Event event;
|
||||
final Timeline timeline;
|
||||
final Color textColor;
|
||||
final Color linkColor;
|
||||
const PollWidget({
|
||||
required this.event,
|
||||
required this.timeline,
|
||||
required this.textColor,
|
||||
required this.linkColor,
|
||||
super.key,
|
||||
});
|
||||
|
||||
void _endPoll(BuildContext context) =>
|
||||
showFutureLoadingDialog(context: context, future: event.endPoll);
|
||||
|
||||
void _toggleVote(BuildContext context, String answerId, int maxSelection) {
|
||||
final userId = event.room.client.userID!;
|
||||
final answerIds = event.getPollResponses(timeline)[userId] ?? {};
|
||||
if (!answerIds.remove(answerId)) {
|
||||
answerIds.add(answerId);
|
||||
if (answerIds.length > maxSelection) {
|
||||
answerIds.clear();
|
||||
answerIds.add(answerId);
|
||||
}
|
||||
}
|
||||
|
||||
showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => event.answerPoll(answerIds.toList()),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final eventContentResult = Result(() => event.parsedPollEventContent);
|
||||
final eventContent = eventContentResult.asValue?.value;
|
||||
if (eventContent == null) {
|
||||
Logs().w('Invalid poll event', eventContentResult.error);
|
||||
return const Text('Unable to parse poll event...');
|
||||
}
|
||||
final responses = event.getPollResponses(timeline);
|
||||
final pollHasBeenEnded = event.getPollHasBeenEnded(timeline);
|
||||
final canVote =
|
||||
event.room.canSendEvent(PollEventContent.responseType) &&
|
||||
!pollHasBeenEnded;
|
||||
final maxPolls = responses.length;
|
||||
final answersVisible =
|
||||
eventContent.pollStartContent.kind == PollKind.disclosed ||
|
||||
pollHasBeenEnded;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
crossAxisAlignment: .start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Linkify(
|
||||
text: eventContent.pollStartContent.question.mText,
|
||||
textScaleFactor: MediaQuery.textScalerOf(context).scale(1),
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: linkColor,
|
||||
),
|
||||
onOpen: (url) => UrlLauncher(context, url.url).launchUrl(),
|
||||
),
|
||||
),
|
||||
Divider(color: linkColor.withAlpha(64)),
|
||||
...eventContent.pollStartContent.answers.map((answer) {
|
||||
final votedUserIds = responses.entries
|
||||
.where((entry) => entry.value.contains(answer.id))
|
||||
.map((entry) => entry.key)
|
||||
.toSet();
|
||||
return Material(
|
||||
color: Colors.transparent,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: CheckboxListTile.adaptive(
|
||||
value:
|
||||
responses[event.room.client.userID!]?.contains(answer.id) ??
|
||||
false,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
checkboxScaleFactor: 1.5,
|
||||
checkboxShape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
),
|
||||
onChanged: !canVote
|
||||
? null
|
||||
: (_) => _toggleVote(
|
||||
context,
|
||||
answer.id,
|
||||
eventContent.pollStartContent.maxSelections,
|
||||
),
|
||||
title: Text(
|
||||
answer.mText,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
),
|
||||
),
|
||||
subtitle: answersVisible
|
||||
? Column(
|
||||
crossAxisAlignment: .start,
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).countVotes(votedUserIds.length),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 2),
|
||||
...votedUserIds.map((userId) {
|
||||
final user = event.room
|
||||
.getState(EventTypes.RoomMember, userId)
|
||||
?.asUser(event.room);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 2.0,
|
||||
),
|
||||
child: Avatar(
|
||||
mxContent: user?.avatarUrl,
|
||||
name:
|
||||
user?.calcDisplayname() ??
|
||||
userId.localpart,
|
||||
size: 12,
|
||||
),
|
||||
);
|
||||
}),
|
||||
const SizedBox(width: 2),
|
||||
],
|
||||
),
|
||||
),
|
||||
LinearProgressIndicator(
|
||||
color: linkColor,
|
||||
backgroundColor: linkColor.withAlpha(128),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius,
|
||||
),
|
||||
value: maxPolls == 0
|
||||
? 0
|
||||
: votedUserIds.length / maxPolls,
|
||||
),
|
||||
],
|
||||
)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
}),
|
||||
if (!pollHasBeenEnded && event.senderId == event.room.client.userID)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: OutlinedButton(
|
||||
onPressed: () => _endPoll(context),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: linkColor,
|
||||
side: BorderSide(color: linkColor.withAlpha(64)),
|
||||
),
|
||||
child: Text(L10n.of(context).endPoll),
|
||||
),
|
||||
)
|
||||
else if (!answersVisible)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
L10n.of(context).answersWillBeVisibleWhenPollHasEnded,
|
||||
style: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: 12,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (pollHasBeenEnded)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
L10n.of(context).pollHasBeenEnded,
|
||||
style: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: 12,
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
110
lib/pages/chat/events/reply_content.dart
Normal file
110
lib/pages/chat/events/reply_content.dart
Normal file
@@ -0,0 +1,110 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../../config/app_config.dart';
|
||||
|
||||
class ReplyContent extends StatelessWidget {
|
||||
final Event replyEvent;
|
||||
final bool ownMessage;
|
||||
final Timeline? timeline;
|
||||
|
||||
const ReplyContent(
|
||||
this.replyEvent, {
|
||||
this.ownMessage = false,
|
||||
super.key,
|
||||
this.timeline,
|
||||
});
|
||||
|
||||
static const BorderRadius borderRadius = BorderRadius.only(
|
||||
topRight: Radius.circular(AppConfig.borderRadius / 2),
|
||||
bottomRight: Radius.circular(AppConfig.borderRadius / 2),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final timeline = this.timeline;
|
||||
final displayEvent = timeline != null
|
||||
? replyEvent.getDisplayEvent(timeline)
|
||||
: replyEvent;
|
||||
const fontSize = AppConfig.messageFontSize;
|
||||
final color = theme.brightness == Brightness.dark
|
||||
? theme.colorScheme.onTertiaryContainer
|
||||
: ownMessage
|
||||
? theme.colorScheme.tertiaryContainer
|
||||
: theme.colorScheme.tertiary;
|
||||
|
||||
return Material(
|
||||
color: Colors.transparent,
|
||||
borderRadius: borderRadius,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: <Widget>[
|
||||
Container(
|
||||
width: 5,
|
||||
height: fontSize * 2 + 16,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Flexible(
|
||||
child: Column(
|
||||
crossAxisAlignment: .start,
|
||||
mainAxisAlignment: .center,
|
||||
children: <Widget>[
|
||||
FutureBuilder<User?>(
|
||||
initialData: displayEvent.senderFromMemoryOrFallback,
|
||||
future: displayEvent.fetchSenderUser(),
|
||||
builder: (context, snapshot) {
|
||||
return Text(
|
||||
'${snapshot.data?.calcDisplayname() ?? displayEvent.senderFromMemoryOrFallback.calcDisplayname()}:',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: color,
|
||||
fontSize: fontSize,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
Text(
|
||||
displayEvent
|
||||
.calcLocalizedBodyFallback(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
withSenderNamePrefix: false,
|
||||
hideReply: true,
|
||||
plaintextBody: true,
|
||||
)
|
||||
.trim()
|
||||
.replaceAll('\n', ' '),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
maxLines: 1,
|
||||
style: TextStyle(
|
||||
color: theme.brightness == Brightness.dark
|
||||
? theme.colorScheme.onSurface
|
||||
: ownMessage
|
||||
? theme.colorScheme.onTertiary
|
||||
: theme.colorScheme.onSurface,
|
||||
fontSize: fontSize,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
123
lib/pages/chat/events/state_message.dart
Normal file
123
lib/pages/chat/events/state_message.dart
Normal file
@@ -0,0 +1,123 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/utd_dialog.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../../config/app_config.dart';
|
||||
|
||||
class StateMessage extends StatelessWidget {
|
||||
final Event event;
|
||||
final void Function()? onExpand;
|
||||
final bool isCollapsed;
|
||||
const StateMessage(
|
||||
this.event, {
|
||||
this.onExpand,
|
||||
this.isCollapsed = false,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AnimatedSize(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: isCollapsed
|
||||
? const SizedBox.shrink()
|
||||
: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: Material(
|
||||
color: theme.colorScheme.surface.withAlpha(128),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius / 3,
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
vertical: 4.0,
|
||||
),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
if (event.type != EventTypes.Encrypted)
|
||||
TextSpan(
|
||||
text: event.calcLocalizedBodyFallback(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
WidgetSpan(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 4.0),
|
||||
child: Avatar(
|
||||
name: event.senderFromMemoryOrFallback
|
||||
.calcDisplayname(),
|
||||
size: 14,
|
||||
mxContent: event
|
||||
.senderFromMemoryOrFallback
|
||||
.avatarUrl,
|
||||
),
|
||||
),
|
||||
),
|
||||
TextSpan(
|
||||
text: L10n.of(context).messageNotDecryptable,
|
||||
),
|
||||
if (!event.redacted)
|
||||
WidgetSpan(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 4.0),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(7),
|
||||
onTap: () =>
|
||||
UtdDialog.show(context, event),
|
||||
child: Icon(
|
||||
Icons.info_outlined,
|
||||
size: 14,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (onExpand != null) ...[
|
||||
const TextSpan(text: '\n'),
|
||||
TextSpan(
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: theme.colorScheme.primary,
|
||||
),
|
||||
recognizer: TapGestureRecognizer()
|
||||
..onTap = onExpand,
|
||||
text: L10n.of(context).moreEvents,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
decoration: event.redacted
|
||||
? TextDecoration.lineThrough
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
163
lib/pages/chat/events/video_player.dart
Normal file
163
lib/pages/chat/events/video_player.dart
Normal file
@@ -0,0 +1,163 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/utils/file_description.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/event_extension.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:tatchat/widgets/blur_hash.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../image_viewer/image_viewer.dart';
|
||||
|
||||
class EventVideoPlayer extends StatelessWidget {
|
||||
final Event event;
|
||||
final Timeline? timeline;
|
||||
final Color? textColor;
|
||||
final Color? linkColor;
|
||||
|
||||
const EventVideoPlayer(
|
||||
this.event, {
|
||||
this.timeline,
|
||||
this.textColor,
|
||||
this.linkColor,
|
||||
super.key,
|
||||
});
|
||||
|
||||
static const String fallbackBlurHash = 'L5H2EC=PM+yV0g-mq.wG9c010J}I';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final supportsVideoPlayer = PlatformInfos.supportsVideoPlayer;
|
||||
|
||||
final blurHash =
|
||||
(event.infoMap as Map<String, dynamic>).tryGet<String>(
|
||||
'xyz.amorgan.blurhash',
|
||||
) ??
|
||||
fallbackBlurHash;
|
||||
final fileDescription = event.fileDescription;
|
||||
const maxDimension = 300.0;
|
||||
final infoMap = event.content.tryGetMap<String, Object?>('info');
|
||||
final videoWidth = infoMap?.tryGet<int>('w') ?? maxDimension;
|
||||
final videoHeight = infoMap?.tryGet<int>('h') ?? maxDimension;
|
||||
|
||||
final modifier = max(videoWidth, videoHeight) / maxDimension;
|
||||
final width = videoWidth / modifier;
|
||||
final height = videoHeight / modifier;
|
||||
|
||||
final durationInt = infoMap?.tryGet<int>('duration');
|
||||
final duration = durationInt == null
|
||||
? null
|
||||
: Duration(milliseconds: durationInt);
|
||||
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
spacing: 8,
|
||||
children: [
|
||||
Material(
|
||||
color: Colors.black,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
child: InkWell(
|
||||
onTap: () => supportsVideoPlayer
|
||||
? showDialog(
|
||||
context: context,
|
||||
builder: (_) => ImageViewer(
|
||||
event,
|
||||
timeline: timeline,
|
||||
outerContext: context,
|
||||
),
|
||||
)
|
||||
: event.saveFile(context),
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
child: SizedBox(
|
||||
width: width,
|
||||
height: height,
|
||||
child: Hero(
|
||||
tag: event.eventId,
|
||||
child: Stack(
|
||||
children: [
|
||||
if (event.hasThumbnail &&
|
||||
AppSettings.showThumbnailsInTimeline.value)
|
||||
MxcImage(
|
||||
event: event,
|
||||
cacheKey: event.transactionId ?? event.eventId,
|
||||
cacheName: event.room.id,
|
||||
isThumbnail: true,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context) => BlurHash(
|
||||
blurhash: blurHash,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
)
|
||||
else
|
||||
BlurHash(
|
||||
blurhash: blurHash,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
Center(
|
||||
child: CircleAvatar(
|
||||
child: supportsVideoPlayer
|
||||
? const Icon(Icons.play_arrow_outlined)
|
||||
: const Icon(Icons.file_download_outlined),
|
||||
),
|
||||
),
|
||||
if (duration != null)
|
||||
Positioned(
|
||||
bottom: 8,
|
||||
left: 16,
|
||||
child: Text(
|
||||
'${duration.inMinutes.toString().padLeft(2, '0')}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
backgroundColor: Colors.black.withAlpha(32),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (fileDescription != null && textColor != null && linkColor != null)
|
||||
SizedBox(
|
||||
width: width,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Linkify(
|
||||
text: fileDescription,
|
||||
textScaleFactor: MediaQuery.textScalerOf(context).scale(1),
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: TextStyle(
|
||||
color: linkColor,
|
||||
fontSize: AppConfig.messageFontSize,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: linkColor,
|
||||
),
|
||||
onOpen: (url) => UrlLauncher(context, url.url).launchUrl(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
37
lib/pages/chat/image_edit_geometry.dart
Normal file
37
lib/pages/chat/image_edit_geometry.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:crop_image/crop_image.dart';
|
||||
|
||||
/// Pure coordinate/rotation helpers for the image editor in
|
||||
/// `send_file_dialog.dart`. Kept dependency-free (only `dart:ui` and
|
||||
/// `crop_image`) so they can be unit-tested without spinning up the app.
|
||||
|
||||
/// Maps a quarter-turn count (positive = clockwise) to the [CropRotation] used
|
||||
/// when baking the final image, so the on-screen `RotatedBox` preview and the
|
||||
/// saved result always rotate the same way.
|
||||
CropRotation imageEditorRotationForQuarterTurns(int quarterTurns) {
|
||||
switch (((quarterTurns % 4) + 4) % 4) {
|
||||
case 1:
|
||||
return CropRotation.right;
|
||||
case 2:
|
||||
return CropRotation.down;
|
||||
case 3:
|
||||
return CropRotation.left;
|
||||
default:
|
||||
return CropRotation.up;
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a pointer position on the draw surface (logical pixels) to a coordinate
|
||||
/// in the source image's pixel space, given the currently shown crop region
|
||||
/// [cropPx] displayed at [displaySize]. The mapping is a uniform scale plus
|
||||
/// translation because the draw surface preserves the crop's aspect ratio.
|
||||
Offset imageEditorLocalToImagePx(Offset local, Size displaySize, Rect cropPx) {
|
||||
final scale = cropPx.width / displaySize.width;
|
||||
return Offset(cropPx.left + local.dx * scale, cropPx.top + local.dy * scale);
|
||||
}
|
||||
475
lib/pages/chat/input_bar.dart
Normal file
475
lib/pages/chat/input_bar.dart
Normal file
@@ -0,0 +1,475 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/trust_user_key_dialog.dart';
|
||||
import 'package:tatchat/utils/markdown_context_builder.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:slugify/slugify.dart';
|
||||
|
||||
import '../../widgets/avatar.dart';
|
||||
import '../../widgets/matrix.dart';
|
||||
import 'command_hints.dart';
|
||||
|
||||
class InputBar extends StatelessWidget {
|
||||
final Room room;
|
||||
final int? minLines;
|
||||
final int? maxLines;
|
||||
final TextInputType? keyboardType;
|
||||
final TextInputAction? textInputAction;
|
||||
final ValueChanged<String>? onSubmitted;
|
||||
final ValueChanged<Uint8List?>? onSubmitImage;
|
||||
final FocusNode? focusNode;
|
||||
final TextEditingController? controller;
|
||||
final InputDecoration decoration;
|
||||
final ValueChanged<String>? onChanged;
|
||||
final bool? autofocus;
|
||||
final bool readOnly;
|
||||
final List<Emoji> suggestionEmojis;
|
||||
|
||||
const InputBar({
|
||||
required this.room,
|
||||
this.minLines,
|
||||
this.maxLines,
|
||||
this.keyboardType,
|
||||
this.onSubmitted,
|
||||
this.onSubmitImage,
|
||||
this.focusNode,
|
||||
this.controller,
|
||||
required this.decoration,
|
||||
this.onChanged,
|
||||
this.autofocus,
|
||||
this.textInputAction,
|
||||
this.readOnly = false,
|
||||
required this.suggestionEmojis,
|
||||
super.key,
|
||||
});
|
||||
|
||||
List<Map<String, String?>> getSuggestions(TextEditingValue text) {
|
||||
if (text.selection.baseOffset != text.selection.extentOffset ||
|
||||
text.selection.baseOffset < 0) {
|
||||
return []; // no entries if there is selected text
|
||||
}
|
||||
final searchText = text.text.substring(0, text.selection.baseOffset);
|
||||
final ret = <Map<String, String?>>[];
|
||||
const maxResults = 30;
|
||||
|
||||
final commandMatch = RegExp(r'^/(\w*)$').firstMatch(searchText);
|
||||
if (commandMatch != null) {
|
||||
final commandSearch = commandMatch[1]!.toLowerCase();
|
||||
for (final command in room.client.commands.keys) {
|
||||
if (command.contains(commandSearch)) {
|
||||
ret.add({'type': 'command', 'name': command});
|
||||
}
|
||||
|
||||
if (ret.length > maxResults) return ret;
|
||||
}
|
||||
}
|
||||
final emojiMatch = RegExp(
|
||||
r'(?:\s|^):(?:([\p{L}\p{N}_-]+)~)?([\p{L}\p{N}_-]+)$',
|
||||
unicode: true,
|
||||
).firstMatch(searchText);
|
||||
if (emojiMatch != null) {
|
||||
final packSearch = emojiMatch[1];
|
||||
final emoteSearch = emojiMatch[2]!.toLowerCase();
|
||||
final emotePacks = room.getImagePacks(ImagePackUsage.emoticon);
|
||||
if (packSearch == null || packSearch.isEmpty) {
|
||||
for (final pack in emotePacks.entries) {
|
||||
for (final emote in pack.value.images.entries) {
|
||||
if (emote.key.toLowerCase().contains(emoteSearch)) {
|
||||
ret.add({
|
||||
'type': 'emote',
|
||||
'name': emote.key,
|
||||
'pack': pack.key,
|
||||
'pack_avatar_url': pack.value.pack.avatarUrl?.toString(),
|
||||
'pack_display_name': pack.value.pack.displayName ?? pack.key,
|
||||
'mxc': emote.value.url.toString(),
|
||||
});
|
||||
}
|
||||
if (ret.length > maxResults) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ret.length > maxResults) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (emotePacks[packSearch] != null) {
|
||||
for (final emote in emotePacks[packSearch]!.images.entries) {
|
||||
if (emote.key.toLowerCase().contains(emoteSearch)) {
|
||||
ret.add({
|
||||
'type': 'emote',
|
||||
'name': emote.key,
|
||||
'pack': packSearch,
|
||||
'pack_avatar_url': emotePacks[packSearch]!.pack.avatarUrl
|
||||
?.toString(),
|
||||
'pack_display_name':
|
||||
emotePacks[packSearch]!.pack.displayName ?? packSearch,
|
||||
'mxc': emote.value.url.toString(),
|
||||
});
|
||||
}
|
||||
if (ret.length > maxResults) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// aside of emote packs, also propose normal (tm) unicode emojis
|
||||
final matchingUnicodeEmojis = suggestionEmojis
|
||||
.where((emoji) => emoji.name.toLowerCase().contains(emoteSearch))
|
||||
.toList();
|
||||
|
||||
// sort by the index of the search term in the name in order to have
|
||||
// best matches first
|
||||
// (thanks for the hint by github.com/nextcloud/circles devs)
|
||||
matchingUnicodeEmojis.sort((a, b) {
|
||||
final indexA = a.name.indexOf(emoteSearch);
|
||||
final indexB = b.name.indexOf(emoteSearch);
|
||||
if (indexA == -1 || indexB == -1) {
|
||||
if (indexA == indexB) return 0;
|
||||
if (indexA == -1) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return indexA.compareTo(indexB);
|
||||
});
|
||||
for (final emoji in matchingUnicodeEmojis) {
|
||||
ret.add({
|
||||
'type': 'emoji',
|
||||
'emoji': emoji.emoji,
|
||||
'label': emoji.name,
|
||||
'current_word': ':$emoteSearch',
|
||||
});
|
||||
if (ret.length > maxResults) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
final userMatch = RegExp(r'(?:\s|^)@([-\w]+)$').firstMatch(searchText);
|
||||
if (userMatch != null) {
|
||||
final userSearch = userMatch[1]!.toLowerCase();
|
||||
for (final user in room.getParticipants()) {
|
||||
if ((user.displayName != null &&
|
||||
(user.displayName!.toLowerCase().contains(userSearch) ||
|
||||
slugify(
|
||||
user.displayName!.toLowerCase(),
|
||||
).contains(userSearch))) ||
|
||||
user.id.localpart!.toLowerCase().contains(userSearch)) {
|
||||
ret.add({
|
||||
'type': 'user',
|
||||
'mxid': user.id,
|
||||
'mention': user.mention,
|
||||
'displayname': user.displayName,
|
||||
'avatar_url': user.avatarUrl?.toString(),
|
||||
});
|
||||
}
|
||||
if (ret.length > maxResults) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
final roomMatch = RegExp(r'(?:\s|^)#([-\w]+)$').firstMatch(searchText);
|
||||
if (roomMatch != null) {
|
||||
final roomSearch = roomMatch[1]!.toLowerCase();
|
||||
for (final r in room.client.rooms) {
|
||||
if (r.getState(EventTypes.RoomTombstone) != null) {
|
||||
continue; // we don't care about tombstoned rooms
|
||||
}
|
||||
final state = r.getState(EventTypes.RoomCanonicalAlias);
|
||||
if ((state != null &&
|
||||
((state.content['alias'] is String &&
|
||||
state.content
|
||||
.tryGet<String>('alias')!
|
||||
.localpart!
|
||||
.toLowerCase()
|
||||
.contains(roomSearch)) ||
|
||||
(state.content['alt_aliases'] is List &&
|
||||
(state.content['alt_aliases'] as List).any(
|
||||
(l) =>
|
||||
l is String &&
|
||||
l.localpart!.toLowerCase().contains(roomSearch),
|
||||
)))) ||
|
||||
(r.name.toLowerCase().contains(roomSearch))) {
|
||||
ret.add({
|
||||
'type': 'room',
|
||||
'mxid': (r.canonicalAlias.isNotEmpty) ? r.canonicalAlias : r.id,
|
||||
'displayname': r.getLocalizedDisplayname(),
|
||||
'avatar_url': r.avatar?.toString(),
|
||||
});
|
||||
}
|
||||
if (ret.length > maxResults) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
Widget buildSuggestion(
|
||||
BuildContext context,
|
||||
Map<String, String?> suggestion,
|
||||
void Function(Map<String, String?>) onSelected,
|
||||
Client? client,
|
||||
) {
|
||||
final theme = Theme.of(context);
|
||||
const size = 30.0;
|
||||
if (suggestion['type'] == 'command') {
|
||||
final command = suggestion['name']!;
|
||||
final hint = commandHint(L10n.of(context), command);
|
||||
return Tooltip(
|
||||
message: hint,
|
||||
waitDuration: const Duration(days: 1), // don't show on hover
|
||||
child: ListTile(
|
||||
onTap: () => onSelected(suggestion),
|
||||
title: Text(
|
||||
commandExample(command),
|
||||
style: const TextStyle(fontFamily: 'RobotoMono'),
|
||||
),
|
||||
subtitle: Text(
|
||||
hint,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (suggestion['type'] == 'emoji') {
|
||||
final label = suggestion['label']!;
|
||||
return Tooltip(
|
||||
message: label,
|
||||
waitDuration: const Duration(days: 1), // don't show on hover
|
||||
child: ListTile(
|
||||
onTap: () => onSelected(suggestion),
|
||||
leading: SizedBox.square(
|
||||
dimension: size,
|
||||
child: Text(
|
||||
suggestion['emoji']!,
|
||||
style: const TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
title: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (suggestion['type'] == 'emote') {
|
||||
return ListTile(
|
||||
onTap: () => onSelected(suggestion),
|
||||
leading: MxcImage(
|
||||
// ensure proper ordering ...
|
||||
key: ValueKey(suggestion['name']),
|
||||
uri: suggestion['mxc'] is String
|
||||
? Uri.parse(suggestion['mxc'] ?? '')
|
||||
: null,
|
||||
width: size,
|
||||
height: size,
|
||||
isThumbnail: false,
|
||||
),
|
||||
title: Row(
|
||||
crossAxisAlignment: .center,
|
||||
children: <Widget>[
|
||||
Text(suggestion['name']!),
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Opacity(
|
||||
opacity: suggestion['pack_avatar_url'] != null ? 0.8 : 0.5,
|
||||
child: suggestion['pack_avatar_url'] != null
|
||||
? Avatar(
|
||||
mxContent: Uri.tryParse(
|
||||
suggestion.tryGet<String>('pack_avatar_url') ?? '',
|
||||
),
|
||||
name: suggestion.tryGet<String>('pack_display_name'),
|
||||
size: size * 0.9,
|
||||
client: client,
|
||||
)
|
||||
: Text(suggestion['pack_display_name']!),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
if (suggestion['type'] == 'user' || suggestion['type'] == 'room') {
|
||||
final url = Uri.parse(suggestion['avatar_url'] ?? '');
|
||||
return ListTile(
|
||||
onTap: () => onSelected(suggestion),
|
||||
leading: Avatar(
|
||||
mxContent: url,
|
||||
name:
|
||||
suggestion.tryGet<String>('displayname') ??
|
||||
suggestion.tryGet<String>('mxid'),
|
||||
size: size,
|
||||
client: client,
|
||||
),
|
||||
title: Text(suggestion['displayname'] ?? suggestion['mxid']!),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
String insertSuggestion(Map<String, String?> suggestion) {
|
||||
final replaceText = controller!.text.substring(
|
||||
0,
|
||||
controller!.selection.baseOffset,
|
||||
);
|
||||
var startText = '';
|
||||
final afterText = replaceText == controller!.text
|
||||
? ''
|
||||
: controller!.text.substring(controller!.selection.baseOffset + 1);
|
||||
var insertText = '';
|
||||
if (suggestion['type'] == 'command') {
|
||||
insertText = '${suggestion['name']!} ';
|
||||
startText = replaceText.replaceAllMapped(
|
||||
RegExp(r'^(/\w*)$'),
|
||||
(Match m) => '/$insertText',
|
||||
);
|
||||
}
|
||||
if (suggestion['type'] == 'emoji') {
|
||||
insertText = '${suggestion['emoji']!} ';
|
||||
startText = replaceText.replaceAllMapped(
|
||||
suggestion['current_word']!,
|
||||
(Match m) => insertText,
|
||||
);
|
||||
}
|
||||
if (suggestion['type'] == 'emote') {
|
||||
var isUnique = true;
|
||||
final insertEmote = suggestion['name'];
|
||||
final insertPack = suggestion['pack'];
|
||||
final emotePacks = room.getImagePacks(ImagePackUsage.emoticon);
|
||||
for (final pack in emotePacks.entries) {
|
||||
if (pack.key == insertPack) {
|
||||
continue;
|
||||
}
|
||||
for (final emote in pack.value.images.entries) {
|
||||
if (emote.key == insertEmote) {
|
||||
isUnique = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isUnique) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
insertText = ':${isUnique ? '' : '${insertPack!}~'}$insertEmote: ';
|
||||
startText = replaceText.replaceAllMapped(
|
||||
RegExp(r'(\s|^)(:(?:[-\w]+~)?[-\w]+)$'),
|
||||
(Match m) => '${m[1]}$insertText',
|
||||
);
|
||||
}
|
||||
if (suggestion['type'] == 'user') {
|
||||
insertText = '${suggestion['mention']!} ';
|
||||
startText = replaceText.replaceAllMapped(
|
||||
RegExp(r'(\s|^)(@[-\w]+)$'),
|
||||
(Match m) => '${m[1]}$insertText',
|
||||
);
|
||||
}
|
||||
if (suggestion['type'] == 'room') {
|
||||
insertText = '${suggestion['mxid']!} ';
|
||||
startText = replaceText.replaceAllMapped(
|
||||
RegExp(r'(\s|^)(#[-\w]+)$'),
|
||||
(Match m) => '${m[1]}$insertText',
|
||||
);
|
||||
}
|
||||
|
||||
return startText + afterText;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Autocomplete<Map<String, String?>>(
|
||||
key: Key('chat_input_field'),
|
||||
focusNode: focusNode,
|
||||
textEditingController: controller,
|
||||
optionsBuilder: getSuggestions,
|
||||
fieldViewBuilder: (context, controller, focusNode, _) => MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(
|
||||
textScaler: TextScaler.linear(AppSettings.fontSizeFactor.value),
|
||||
),
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
focusNode: focusNode,
|
||||
readOnly: readOnly,
|
||||
onEditingComplete: () {
|
||||
// To not lose focus on iOS:
|
||||
// https://github.com/krille-chan/fluffychat/issues/2784
|
||||
},
|
||||
contextMenuBuilder: (c, e) => MarkdownContextBuilder(
|
||||
editableTextState: e,
|
||||
controller: controller,
|
||||
),
|
||||
contentInsertionConfiguration: ContentInsertionConfiguration(
|
||||
onContentInserted: (KeyboardInsertedContent content) async {
|
||||
final proceed = await showTrustUserInRoomDialog(context, room);
|
||||
if (!proceed) return;
|
||||
final data = content.data;
|
||||
if (data == null) return;
|
||||
|
||||
final file = MatrixFile(
|
||||
mimeType: content.mimeType,
|
||||
bytes: data,
|
||||
name: content.uri.split('/').last,
|
||||
);
|
||||
room.sendFileEvent(file, shrinkImageMaxDimension: 1600);
|
||||
},
|
||||
),
|
||||
minLines: minLines,
|
||||
maxLines: maxLines,
|
||||
keyboardType: keyboardType,
|
||||
textInputAction: textInputAction,
|
||||
autofocus: autofocus!,
|
||||
inputFormatters: [
|
||||
LengthLimitingTextInputFormatter((maxPDUSize / 3).floor()),
|
||||
],
|
||||
onSubmitted: (text) {
|
||||
// fix for library for now
|
||||
// it sets the types for the callback incorrectly
|
||||
onSubmitted!(text);
|
||||
},
|
||||
maxLength: AppSettings.textMessageMaxLength.value,
|
||||
decoration: decoration,
|
||||
onChanged: (text) {
|
||||
// fix for the library for now
|
||||
// it sets the types for the callback incorrectly
|
||||
onChanged!(text);
|
||||
},
|
||||
textCapitalization: TextCapitalization.sentences,
|
||||
),
|
||||
),
|
||||
optionsViewBuilder: (c, onSelected, s) {
|
||||
final suggestions = s.toList();
|
||||
return Material(
|
||||
elevation: theme.appBarTheme.scrolledUnderElevation ?? 4,
|
||||
shadowColor: theme.appBarTheme.shadowColor,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: ListView.builder(
|
||||
padding: EdgeInsets.zero,
|
||||
shrinkWrap: true,
|
||||
itemCount: suggestions.length,
|
||||
itemBuilder: (context, i) => buildSuggestion(
|
||||
c,
|
||||
suggestions[i],
|
||||
onSelected,
|
||||
Matrix.of(context).client,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
displayStringForOption: insertSuggestion,
|
||||
optionsViewOpenDirection: OptionsViewOpenDirection.up,
|
||||
);
|
||||
}
|
||||
}
|
||||
104
lib/pages/chat/pinned_events.dart
Normal file
104
lib/pages/chat/pinned_events.dart
Normal file
@@ -0,0 +1,104 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/chat.dart';
|
||||
import 'package:tatchat/pages/chat/chat_app_bar_list_tile.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_modal_action_popup.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class PinnedEvents extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
|
||||
const PinnedEvents(this.controller, {super.key});
|
||||
|
||||
Future<void> _displayPinnedEventsDialog(BuildContext context) async {
|
||||
final l10n = L10n.of(context);
|
||||
final eventsResult = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => Future.wait(
|
||||
controller.room.pinnedEventIds.map(
|
||||
(eventId) => controller.room.getEventById(eventId),
|
||||
),
|
||||
),
|
||||
);
|
||||
final events = eventsResult.result;
|
||||
if (events == null) return;
|
||||
if (!context.mounted) return;
|
||||
|
||||
final eventId = events.length == 1
|
||||
? events.single?.eventId
|
||||
: await showModalActionPopup<String>(
|
||||
context: context,
|
||||
title: l10n.pin,
|
||||
cancelLabel: l10n.cancel,
|
||||
actions: events
|
||||
.map(
|
||||
(event) => AdaptiveModalAction(
|
||||
value: event?.eventId ?? '',
|
||||
icon: const Icon(Icons.push_pin_outlined),
|
||||
label:
|
||||
event
|
||||
?.calcLocalizedBodyFallback(
|
||||
MatrixLocals(l10n),
|
||||
withSenderNamePrefix: true,
|
||||
hideReply: true,
|
||||
)
|
||||
.trim()
|
||||
.replaceAll('\n', ' ') ??
|
||||
'UNKNOWN',
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
|
||||
if (eventId != null) controller.scrollToEventId(eventId);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final pinnedEventIds = controller.room.pinnedEventIds;
|
||||
|
||||
if (pinnedEventIds.isEmpty || controller.activeThreadId != null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return FutureBuilder<Event?>(
|
||||
future: controller.room.getEventById(pinnedEventIds.last),
|
||||
builder: (context, snapshot) {
|
||||
final event = snapshot.data;
|
||||
return ChatAppBarListTile(
|
||||
title:
|
||||
event
|
||||
?.calcLocalizedBodyFallback(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
withSenderNamePrefix: true,
|
||||
hideReply: true,
|
||||
)
|
||||
.replaceAll('\n', ' ') ??
|
||||
L10n.of(context).loadingPleaseWait,
|
||||
leading: IconButton(
|
||||
splashRadius: 18,
|
||||
iconSize: 18,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
icon: const Icon(Icons.push_pin),
|
||||
tooltip: L10n.of(context).unpin,
|
||||
onPressed: controller.room.canSendEvent(EventTypes.RoomPinnedEvents)
|
||||
? () => controller.unpinEvent(event!.eventId)
|
||||
: null,
|
||||
),
|
||||
onTap: () => _displayPinnedEventsDialog(context),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
107
lib/pages/chat/recording_input_row.dart
Normal file
107
lib/pages/chat/recording_input_row.dart
Normal file
@@ -0,0 +1,107 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/chat_input_row.dart';
|
||||
import 'package:tatchat/pages/chat/recording_view_model.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class RecordingInputRow extends StatelessWidget {
|
||||
final RecordingViewModelState state;
|
||||
final Future<void> Function(String, int, List<int>, String) onSend;
|
||||
const RecordingInputRow({
|
||||
required this.state,
|
||||
required this.onSend,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
const maxDecibalWidth = 36.0;
|
||||
final time =
|
||||
'${state.duration.inMinutes.toString().padLeft(2, '0')}:${(state.duration.inSeconds % 60).toString().padLeft(2, '0')}';
|
||||
return SizedBox(
|
||||
height: ChatInputRow.height,
|
||||
child: Row(
|
||||
crossAxisAlignment: .center,
|
||||
mainAxisAlignment: .spaceBetween,
|
||||
children: [
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
alignment: .center,
|
||||
width: 48,
|
||||
child: IconButton(
|
||||
tooltip: L10n.of(context).cancel,
|
||||
icon: const Icon(Icons.delete_outlined),
|
||||
color: theme.colorScheme.error,
|
||||
onPressed: state.cancel,
|
||||
),
|
||||
),
|
||||
if (state.isPaused)
|
||||
Container(
|
||||
alignment: .center,
|
||||
width: 48,
|
||||
child: IconButton(
|
||||
tooltip: L10n.of(context).resume,
|
||||
icon: const Icon(Icons.play_circle_outline_outlined),
|
||||
onPressed: state.resume,
|
||||
),
|
||||
)
|
||||
else
|
||||
Container(
|
||||
alignment: .center,
|
||||
width: 48,
|
||||
child: IconButton(
|
||||
tooltip: L10n.of(context).pause,
|
||||
icon: const Icon(Icons.pause_circle_outline_outlined),
|
||||
onPressed: state.pause,
|
||||
),
|
||||
),
|
||||
Text(time),
|
||||
Expanded(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
const width = 4;
|
||||
return Row(
|
||||
mainAxisSize: .min,
|
||||
mainAxisAlignment: .end,
|
||||
children: state.amplitudeTimeline.reversed
|
||||
.take((constraints.maxWidth / (width + 2)).floor())
|
||||
.toList()
|
||||
.reversed
|
||||
.map(
|
||||
(amplitude) => Container(
|
||||
margin: const EdgeInsets.only(left: 2),
|
||||
width: width.toDouble(),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
height: maxDecibalWidth * (amplitude / 100),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
style: IconButton.styleFrom(
|
||||
disabledBackgroundColor: theme.bubbleColor.withAlpha(128),
|
||||
backgroundColor: theme.bubbleColor,
|
||||
foregroundColor: theme.onBubbleColor,
|
||||
),
|
||||
tooltip: L10n.of(context).sendAudio,
|
||||
icon: const Icon(Icons.send_outlined),
|
||||
onPressed: () => state.stopAndSend(onSend),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
222
lib/pages/chat/recording_view_model.dart
Normal file
222
lib/pages/chat/recording_view_model.dart
Normal file
@@ -0,0 +1,222 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:path/path.dart' as path_lib;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:record/record.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
|
||||
import 'events/audio_player.dart';
|
||||
|
||||
class RecordingViewModel extends StatefulWidget {
|
||||
final Widget Function(BuildContext, RecordingViewModelState) builder;
|
||||
|
||||
const RecordingViewModel({required this.builder, super.key});
|
||||
|
||||
@override
|
||||
RecordingViewModelState createState() => RecordingViewModelState();
|
||||
}
|
||||
|
||||
class RecordingViewModelState extends State<RecordingViewModel> {
|
||||
Timer? _recorderSubscription;
|
||||
Duration duration = Duration.zero;
|
||||
|
||||
bool get isRecording => _audioRecorder != null;
|
||||
|
||||
AudioRecorder? _audioRecorder;
|
||||
final List<double> amplitudeTimeline = [];
|
||||
|
||||
String? fileName;
|
||||
|
||||
bool isPaused = false;
|
||||
|
||||
Future<void> startRecording(Room room) async {
|
||||
room.client.getConfig(); // Preload server file configuration.
|
||||
if (PlatformInfos.isAndroid) {
|
||||
final info = await DeviceInfoPlugin().androidInfo;
|
||||
if (!mounted) return;
|
||||
if (info.version.sdkInt < 19) {
|
||||
showOkAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).unsupportedAndroidVersion,
|
||||
message: L10n.of(context).unsupportedAndroidVersionLong,
|
||||
okLabel: L10n.of(context).close,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (await AudioRecorder().hasPermission() == false) return;
|
||||
|
||||
final audioRecorder = _audioRecorder ??= AudioRecorder();
|
||||
setState(() {});
|
||||
|
||||
try {
|
||||
final codec =
|
||||
!PlatformInfos
|
||||
.isIOS && // Blocked by https://github.com/llfbandit/record/issues/560
|
||||
await audioRecorder.isEncoderSupported(AudioEncoder.opus)
|
||||
? AudioEncoder.opus
|
||||
: AudioEncoder.aacLc;
|
||||
fileName =
|
||||
'voice_message_${DateTime.now().millisecondsSinceEpoch}.${codec.fileExtension}';
|
||||
String? path;
|
||||
if (!kIsWeb) {
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
path = path_lib.join(tempDir.path, fileName);
|
||||
}
|
||||
|
||||
final result = await audioRecorder.hasPermission();
|
||||
if (result != true) {
|
||||
if (!mounted) return;
|
||||
showOkAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).oopsSomethingWentWrong,
|
||||
message: L10n.of(context).noPermission,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await WakelockPlus.enable();
|
||||
|
||||
await audioRecorder.start(
|
||||
RecordConfig(
|
||||
bitRate: AppSettings.audioRecordingBitRate.value,
|
||||
sampleRate: AppSettings.audioRecordingSamplingRate.value,
|
||||
numChannels: AppSettings.audioRecordingNumChannels.value,
|
||||
autoGain: AppSettings.audioRecordingAutoGain.value,
|
||||
echoCancel: AppSettings.audioRecordingEchoCancel.value,
|
||||
noiseSuppress: AppSettings.audioRecordingNoiseSuppress.value,
|
||||
encoder: codec,
|
||||
),
|
||||
path: path ?? '',
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() => duration = Duration.zero);
|
||||
_subscribe();
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to start voice message recording', e, s);
|
||||
if (!mounted) return;
|
||||
showOkAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).oopsSomethingWentWrong,
|
||||
message: e.toString(),
|
||||
);
|
||||
setState(_reset);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_reset();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _subscribe() {
|
||||
_recorderSubscription?.cancel();
|
||||
_recorderSubscription = Timer.periodic(const Duration(milliseconds: 100), (
|
||||
_,
|
||||
) async {
|
||||
final amplitude = await _audioRecorder!.getAmplitude();
|
||||
var value = 100 + amplitude.current * 2;
|
||||
value = value < 1 ? 1 : value;
|
||||
amplitudeTimeline.add(value);
|
||||
setState(() {
|
||||
duration += const Duration(milliseconds: 100);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
WakelockPlus.disable();
|
||||
_recorderSubscription?.cancel();
|
||||
_audioRecorder?.stop();
|
||||
_audioRecorder = null;
|
||||
|
||||
fileName = null;
|
||||
duration = Duration.zero;
|
||||
amplitudeTimeline.clear();
|
||||
isPaused = false;
|
||||
}
|
||||
|
||||
void cancel() {
|
||||
setState(_reset);
|
||||
}
|
||||
|
||||
void pause() {
|
||||
_audioRecorder?.pause();
|
||||
_recorderSubscription?.cancel();
|
||||
setState(() {
|
||||
isPaused = true;
|
||||
});
|
||||
}
|
||||
|
||||
void resume() {
|
||||
_audioRecorder?.resume();
|
||||
_subscribe();
|
||||
setState(() {
|
||||
isPaused = false;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> stopAndSend(
|
||||
Future<void> Function(
|
||||
String path,
|
||||
int duration,
|
||||
List<int> waveform,
|
||||
String fileName,
|
||||
)
|
||||
onSend,
|
||||
) async {
|
||||
_recorderSubscription?.cancel();
|
||||
final path = await _audioRecorder?.stop();
|
||||
|
||||
if (path == null) throw ('Recording failed!');
|
||||
const waveCount = AudioPlayerWidget.wavesCount;
|
||||
final step = amplitudeTimeline.length < waveCount
|
||||
? 1
|
||||
: (amplitudeTimeline.length / waveCount).round();
|
||||
final waveform = <int>[];
|
||||
for (var i = 0; i < amplitudeTimeline.length; i += step) {
|
||||
waveform.add((amplitudeTimeline[i] / 100 * 1024).round());
|
||||
}
|
||||
|
||||
onSend(path, duration.inMilliseconds, waveform, fileName!);
|
||||
|
||||
cancel();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => widget.builder(context, this);
|
||||
}
|
||||
|
||||
extension on AudioEncoder {
|
||||
String get fileExtension {
|
||||
switch (this) {
|
||||
case AudioEncoder.aacLc:
|
||||
case AudioEncoder.aacEld:
|
||||
case AudioEncoder.aacHe:
|
||||
return 'm4a';
|
||||
case AudioEncoder.opus:
|
||||
return 'ogg';
|
||||
case AudioEncoder.wav:
|
||||
return 'wav';
|
||||
case AudioEncoder.amrNb:
|
||||
case AudioEncoder.amrWb:
|
||||
case AudioEncoder.flac:
|
||||
case AudioEncoder.pcm16bits:
|
||||
throw UnsupportedError('Not yet used');
|
||||
}
|
||||
}
|
||||
}
|
||||
95
lib/pages/chat/reply_display.dart
Normal file
95
lib/pages/chat/reply_display.dart
Normal file
@@ -0,0 +1,95 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../config/themes.dart';
|
||||
import 'chat.dart';
|
||||
import 'events/reply_content.dart';
|
||||
|
||||
class ReplyDisplay extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
const ReplyDisplay(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return AnimatedSize(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: controller.editEvent != null || controller.replyEvent != null
|
||||
? Material(
|
||||
color: theme.colorScheme.surfaceContainer,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: IconButton(
|
||||
tooltip: L10n.of(context).close,
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: controller.cancelReplyEventAction,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: controller.replyEvent != null
|
||||
? ReplyContent(
|
||||
controller.replyEvent!,
|
||||
timeline: controller.timeline,
|
||||
)
|
||||
: _EditContent(
|
||||
controller.editEvent?.getDisplayEvent(
|
||||
controller.timeline!,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
: SizedBox.shrink(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _EditContent extends StatelessWidget {
|
||||
final Event? event;
|
||||
|
||||
const _EditContent(this.event);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final event = this.event;
|
||||
if (event == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Row(
|
||||
children: <Widget>[
|
||||
Icon(Icons.edit, color: theme.colorScheme.primary),
|
||||
Container(width: 15.0),
|
||||
Text(
|
||||
event
|
||||
.calcLocalizedBodyFallback(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
withSenderNamePrefix: false,
|
||||
hideReply: true,
|
||||
)
|
||||
.trim()
|
||||
.replaceAll('\n', ' '),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
maxLines: 1,
|
||||
style: TextStyle(color: theme.textTheme.bodyMedium!.color),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
94
lib/pages/chat/seen_by_row.dart
Normal file
94
lib/pages/chat/seen_by_row.dart
Normal file
@@ -0,0 +1,94 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class SeenByRow extends StatelessWidget {
|
||||
final Event event;
|
||||
const SeenByRow({super.key, required this.event});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
const maxAvatars = 7;
|
||||
return StreamBuilder(
|
||||
stream: event.room.client.onSync.stream.where(
|
||||
(syncUpdate) =>
|
||||
syncUpdate.rooms?.join?[event.room.id]?.ephemeral?.any(
|
||||
(ephemeral) => ephemeral.type == 'm.receipt',
|
||||
) ??
|
||||
false,
|
||||
),
|
||||
builder: (context, asyncSnapshot) {
|
||||
final seenByUsers = event.receipts
|
||||
.map((r) => r.user)
|
||||
.where(
|
||||
(user) =>
|
||||
user.id != event.room.client.userID &&
|
||||
user.id != event.senderId,
|
||||
)
|
||||
.toList();
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
alignment: Alignment.center,
|
||||
child: AnimatedContainer(
|
||||
constraints: const BoxConstraints(
|
||||
maxWidth: FluffyThemes.maxTimelineWidth,
|
||||
),
|
||||
height: seenByUsers.isEmpty ? 0 : 24,
|
||||
duration: seenByUsers.isEmpty
|
||||
? Duration.zero
|
||||
: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
alignment: event.senderId == Matrix.of(context).client.userID
|
||||
? Alignment.topRight
|
||||
: Alignment.topLeft,
|
||||
padding: const EdgeInsets.only(
|
||||
bottom: 4,
|
||||
top: 1,
|
||||
left: 8,
|
||||
right: 8,
|
||||
),
|
||||
child: Wrap(
|
||||
spacing: 4,
|
||||
children: [
|
||||
...(seenByUsers.length > maxAvatars
|
||||
? seenByUsers.sublist(0, maxAvatars)
|
||||
: seenByUsers)
|
||||
.map(
|
||||
(user) => Avatar(
|
||||
mxContent: user.avatarUrl,
|
||||
name: user.calcDisplayname(),
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
if (seenByUsers.length > maxAvatars)
|
||||
SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: Material(
|
||||
color: theme.colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'+${seenByUsers.length - maxAvatars}',
|
||||
style: const TextStyle(fontSize: 9),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
1205
lib/pages/chat/send_file_dialog.dart
Normal file
1205
lib/pages/chat/send_file_dialog.dart
Normal file
File diff suppressed because it is too large
Load Diff
136
lib/pages/chat/send_location_dialog.dart
Normal file
136
lib/pages/chat/send_location_dialog.dart
Normal file
@@ -0,0 +1,136 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/events/map_bubble.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/adaptive_dialog_action.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class SendLocationDialog extends StatefulWidget {
|
||||
final Room room;
|
||||
|
||||
const SendLocationDialog({required this.room, super.key});
|
||||
|
||||
@override
|
||||
SendLocationDialogState createState() => SendLocationDialogState();
|
||||
}
|
||||
|
||||
class SendLocationDialogState extends State<SendLocationDialog> {
|
||||
bool disabled = false;
|
||||
bool denied = false;
|
||||
bool isSending = false;
|
||||
Position? position;
|
||||
Object? error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
requestLocation();
|
||||
}
|
||||
|
||||
Future<void> requestLocation() async {
|
||||
if (!(await Geolocator.isLocationServiceEnabled())) {
|
||||
setState(() => disabled = true);
|
||||
return;
|
||||
}
|
||||
var permission = await Geolocator.checkPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
permission = await Geolocator.requestPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
setState(() => denied = true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (permission == LocationPermission.deniedForever) {
|
||||
setState(() => denied = true);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Position position;
|
||||
try {
|
||||
position = await Geolocator.getCurrentPosition(
|
||||
locationSettings: const LocationSettings(
|
||||
accuracy: LocationAccuracy.best,
|
||||
timeLimit: Duration(seconds: 30),
|
||||
),
|
||||
);
|
||||
} on TimeoutException {
|
||||
position = await Geolocator.getCurrentPosition(
|
||||
locationSettings: const LocationSettings(
|
||||
accuracy: LocationAccuracy.medium,
|
||||
timeLimit: Duration(seconds: 30),
|
||||
),
|
||||
);
|
||||
}
|
||||
setState(() => this.position = position);
|
||||
} catch (e) {
|
||||
setState(() => error = e);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> sendAction() async {
|
||||
setState(() => isSending = true);
|
||||
final body =
|
||||
'https://www.openstreetmap.org/?mlat=${position!.latitude}&mlon=${position!.longitude}#map=16/${position!.latitude}/${position!.longitude}';
|
||||
final uri =
|
||||
'geo:${position!.latitude},${position!.longitude};u=${position!.accuracy}';
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => widget.room.sendLocation(body, uri),
|
||||
);
|
||||
if (!mounted) return;
|
||||
Navigator.of(context, rootNavigator: false).pop();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget contentWidget;
|
||||
if (position != null) {
|
||||
contentWidget = MapBubble(
|
||||
latitude: position!.latitude,
|
||||
longitude: position!.longitude,
|
||||
);
|
||||
} else if (disabled) {
|
||||
contentWidget = Text(L10n.of(context).locationDisabledNotice);
|
||||
} else if (denied) {
|
||||
contentWidget = Text(L10n.of(context).locationPermissionDeniedNotice);
|
||||
} else if (error != null) {
|
||||
contentWidget = Text(
|
||||
L10n.of(context).errorObtainingLocation(error.toString()),
|
||||
);
|
||||
} else {
|
||||
contentWidget = Row(
|
||||
mainAxisSize: .min,
|
||||
mainAxisAlignment: .center,
|
||||
children: [
|
||||
const CupertinoActivityIndicator(),
|
||||
const SizedBox(width: 12),
|
||||
Text(L10n.of(context).obtainingLocation),
|
||||
],
|
||||
);
|
||||
}
|
||||
return AlertDialog.adaptive(
|
||||
title: Text(L10n.of(context).shareLocation),
|
||||
content: contentWidget,
|
||||
actions: [
|
||||
AdaptiveDialogAction(
|
||||
onPressed: Navigator.of(context, rootNavigator: false).pop,
|
||||
child: Text(L10n.of(context).cancel),
|
||||
),
|
||||
if (position != null)
|
||||
AdaptiveDialogAction(
|
||||
onPressed: isSending ? null : sendAction,
|
||||
child: Text(L10n.of(context).send),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
174
lib/pages/chat/start_poll_bottom_sheet.dart
Normal file
174
lib/pages/chat/start_poll_bottom_sheet.dart
Normal file
@@ -0,0 +1,174 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/trust_user_key_dialog.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class StartPollBottomSheet extends StatefulWidget {
|
||||
final Room room;
|
||||
const StartPollBottomSheet({required this.room, super.key});
|
||||
|
||||
@override
|
||||
State<StartPollBottomSheet> createState() => _StartPollBottomSheetState();
|
||||
}
|
||||
|
||||
class _StartPollBottomSheetState extends State<StartPollBottomSheet> {
|
||||
final TextEditingController _bodyController = TextEditingController();
|
||||
bool _allowMultipleAnswers = false;
|
||||
final List<TextEditingController> _answers = [
|
||||
TextEditingController(),
|
||||
TextEditingController(),
|
||||
];
|
||||
PollKind _pollKind = PollKind.disclosed;
|
||||
|
||||
bool _canCreate = false;
|
||||
|
||||
bool isLoading = false;
|
||||
|
||||
String? _txid;
|
||||
|
||||
Future<void> _createPoll() async {
|
||||
final proceed = await showTrustUserInRoomDialog(context, widget.room);
|
||||
if (!proceed || !mounted) return;
|
||||
try {
|
||||
var id = 0;
|
||||
_txid ??= widget.room.client.generateUniqueTransactionId();
|
||||
await widget.room.startPoll(
|
||||
question: _bodyController.text.trim(),
|
||||
answers: _answers
|
||||
.map(
|
||||
(answerController) => PollAnswer(
|
||||
id: (++id).toString(),
|
||||
mText: answerController.text.trim(),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
kind: _pollKind,
|
||||
maxSelections: _allowMultipleAnswers ? _answers.length : 1,
|
||||
txid: _txid,
|
||||
);
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).pop();
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to create poll', e, s);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
}
|
||||
}
|
||||
|
||||
void _updateCanCreate([_]) {
|
||||
final newCanCreate =
|
||||
_bodyController.text.trim().isNotEmpty &&
|
||||
!_answers.any((controller) => controller.text.trim().isEmpty);
|
||||
if (_canCreate != newCanCreate) {
|
||||
setState(() {
|
||||
_canCreate = newCanCreate;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_bodyController.dispose();
|
||||
for (final answerController in _answers) {
|
||||
answerController.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const maxAnswers = 10;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: CloseButton(onPressed: Navigator.of(context).pop),
|
||||
title: Text(L10n.of(context).startPoll),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
|
||||
children: [
|
||||
TextField(
|
||||
controller: _bodyController,
|
||||
minLines: 2,
|
||||
maxLines: 4,
|
||||
maxLength: 1024,
|
||||
onChanged: _updateCanCreate,
|
||||
decoration: InputDecoration(
|
||||
hintText: L10n.of(context).pollQuestion,
|
||||
counter: const SizedBox.shrink(),
|
||||
),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
..._answers.map(
|
||||
(answerController) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16.0),
|
||||
child: TextField(
|
||||
controller: answerController,
|
||||
onChanged: _updateCanCreate,
|
||||
maxLength: 64,
|
||||
decoration: InputDecoration(
|
||||
counter: const SizedBox.shrink(),
|
||||
hintText: L10n.of(context).answerOption,
|
||||
suffixIcon: _answers.length == 2
|
||||
? null
|
||||
: IconButton(
|
||||
icon: const Icon(Icons.cancel_outlined),
|
||||
onPressed: () => setState(() {
|
||||
_answers.remove(answerController..dispose());
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: TextButton.icon(
|
||||
icon: const Icon(Icons.add_outlined),
|
||||
onPressed: _answers.length < maxAnswers
|
||||
? () => setState(() {
|
||||
_answers.add(TextEditingController());
|
||||
})
|
||||
: null,
|
||||
label: Text(L10n.of(context).addAnswerOption),
|
||||
),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: Switch.adaptive(
|
||||
value: _pollKind == PollKind.disclosed,
|
||||
onChanged: (allow) => setState(() {
|
||||
_pollKind = allow ? PollKind.disclosed : PollKind.undisclosed;
|
||||
}),
|
||||
),
|
||||
title: Text(L10n.of(context).answersVisible),
|
||||
),
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: Switch.adaptive(
|
||||
value: _allowMultipleAnswers,
|
||||
onChanged: (allow) => setState(() {
|
||||
_allowMultipleAnswers = allow;
|
||||
}),
|
||||
),
|
||||
title: Text(L10n.of(context).allowMultipleAnswers),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: !isLoading && _canCreate ? _createPoll : null,
|
||||
child: isLoading
|
||||
? const LinearProgressIndicator()
|
||||
: Text(L10n.of(context).startPoll),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
187
lib/pages/chat/sticker_picker_dialog.dart
Normal file
187
lib/pages/chat/sticker_picker_dialog.dart
Normal file
@@ -0,0 +1,187 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../widgets/avatar.dart';
|
||||
|
||||
class StickerPickerDialog extends StatefulWidget {
|
||||
final Room room;
|
||||
final ImagePackUsage usage;
|
||||
final void Function(ImagePackImageContent) onSelected;
|
||||
|
||||
const StickerPickerDialog({
|
||||
required this.onSelected,
|
||||
required this.room,
|
||||
this.usage = ImagePackUsage.sticker,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
StickerPickerDialogState createState() => StickerPickerDialogState();
|
||||
}
|
||||
|
||||
class StickerPickerDialogState extends State<StickerPickerDialog> {
|
||||
String? searchFilter;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final stickerPacks = widget.room.getImagePacks(widget.usage);
|
||||
final packSlugs = stickerPacks.keys.toList();
|
||||
|
||||
return Material(
|
||||
color: theme.colorScheme.onInverseSurface,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: CustomScrollView(
|
||||
slivers: <Widget>[
|
||||
SliverAppBar(
|
||||
floating: true,
|
||||
primary: false,
|
||||
toolbarHeight: 72,
|
||||
scrolledUnderElevation: 0,
|
||||
backgroundColor: Colors.transparent,
|
||||
automaticallyImplyLeading: false,
|
||||
title: TextField(
|
||||
autofocus: false,
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.secondaryContainer,
|
||||
border: OutlineInputBorder(
|
||||
borderSide: BorderSide.none,
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
hintText: L10n.of(context).search,
|
||||
hintStyle: TextStyle(
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
floatingLabelBehavior: FloatingLabelBehavior.never,
|
||||
prefixIcon: const Icon(Icons.search_outlined),
|
||||
),
|
||||
onChanged: (s) => setState(() => searchFilter = s),
|
||||
),
|
||||
),
|
||||
if (packSlugs.isEmpty)
|
||||
SliverFillRemaining(
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Text(L10n.of(context).noEmotesFound),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => UrlLauncher(
|
||||
context,
|
||||
AppConfig.howDoIGetStickersTutorial,
|
||||
).launchUrl(),
|
||||
icon: const Icon(Icons.explore_outlined),
|
||||
label: Text(L10n.of(context).discover),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverList.builder(
|
||||
itemCount: packSlugs.length,
|
||||
itemBuilder: (BuildContext context, int packIndex) {
|
||||
final pack = stickerPacks[packSlugs[packIndex]]!;
|
||||
final filteredImagePackImageEntried = pack.images.entries
|
||||
.toList();
|
||||
if (searchFilter?.isNotEmpty ?? false) {
|
||||
filteredImagePackImageEntried.removeWhere(
|
||||
(e) =>
|
||||
!(e.key.toLowerCase().contains(
|
||||
searchFilter!.toLowerCase(),
|
||||
) ||
|
||||
(e.value.body?.toLowerCase().contains(
|
||||
searchFilter!.toLowerCase(),
|
||||
) ??
|
||||
false)),
|
||||
);
|
||||
}
|
||||
final imageKeys = filteredImagePackImageEntried
|
||||
.map((e) => e.key)
|
||||
.toList();
|
||||
if (imageKeys.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final packName =
|
||||
pack.pack.displayName ?? packSlugs[packIndex];
|
||||
return Column(
|
||||
children: <Widget>[
|
||||
if (packIndex != 0) const SizedBox(height: 20),
|
||||
if (packName != 'user')
|
||||
ListTile(
|
||||
leading: Avatar(
|
||||
mxContent: pack.pack.avatarUrl,
|
||||
name: packName,
|
||||
client: widget.room.client,
|
||||
),
|
||||
title: Text(packName),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
GridView.builder(
|
||||
padding: EdgeInsets.zero,
|
||||
itemCount: imageKeys.length,
|
||||
gridDelegate:
|
||||
const SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: 84,
|
||||
mainAxisSpacing: 8.0,
|
||||
crossAxisSpacing: 8.0,
|
||||
),
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemBuilder: (BuildContext context, int imageIndex) {
|
||||
final image = pack.images[imageKeys[imageIndex]]!;
|
||||
return Tooltip(
|
||||
message: image.body ?? imageKeys[imageIndex],
|
||||
child: InkWell(
|
||||
radius: AppConfig.borderRadius,
|
||||
key: ValueKey(image.url.toString()),
|
||||
onTap: () {
|
||||
// copy the image
|
||||
final imageCopy =
|
||||
ImagePackImageContent.fromJson(
|
||||
image.toJson().copy(),
|
||||
);
|
||||
// set the body, if it doesn't exist, to the key
|
||||
imageCopy.body ??= imageKeys[imageIndex];
|
||||
widget.onSelected(imageCopy);
|
||||
},
|
||||
child: AbsorbPointer(
|
||||
absorbing: true,
|
||||
child: MxcImage(
|
||||
uri: image.url,
|
||||
fit: BoxFit.contain,
|
||||
width: 128,
|
||||
height: 128,
|
||||
animated: true,
|
||||
isThumbnail: false,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
163
lib/pages/chat/trust_user_key_dialog.dart
Normal file
163
lib/pages/chat/trust_user_key_dialog.dart
Normal file
@@ -0,0 +1,163 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/key_verification/key_verification_dialog.dart';
|
||||
import 'package:tatchat/utils/beautify_string_extension.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/adaptive_dialog_action.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/dialog_text_field.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
Future<bool> showTrustUserInRoomDialog(BuildContext context, Room room) async {
|
||||
if (!room.encrypted) return true;
|
||||
|
||||
final users = await room.requestParticipants();
|
||||
if (!context.mounted) return false;
|
||||
|
||||
users.removeWhere((user) {
|
||||
if (user.id == room.client.userID) return true;
|
||||
final keys = room.client.userDeviceKeys[user.id];
|
||||
final masterKey = keys?.masterKey;
|
||||
|
||||
if (keys == null ||
|
||||
masterKey == null ||
|
||||
masterKey.verified ||
|
||||
masterKey.trustOnFirstUseSince != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (users.isEmpty) return true;
|
||||
|
||||
final l10n = L10n.of(context);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final action = await showAdaptiveDialog<_Action>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog.adaptive(
|
||||
title: Center(
|
||||
child: Icon(
|
||||
Icons.lock_outlined,
|
||||
size: 32,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
content: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: 128),
|
||||
child: SelectionArea(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: .stretch,
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
Center(
|
||||
child: Text(
|
||||
users.length == 1
|
||||
? l10n.messageCanOnlyBeReadByUser
|
||||
: l10n.messageCanOnlyBeReadByUsers,
|
||||
style: TextStyle(fontSize: 16),
|
||||
textAlign: .center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
for (final user in users) ...[
|
||||
Row(
|
||||
children: [
|
||||
Avatar(
|
||||
name: user.calcDisplayname(),
|
||||
mxContent: user.avatarUrl,
|
||||
size: 14,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: Text(
|
||||
user.calcDisplayname(),
|
||||
style: theme.textTheme.labelSmall,
|
||||
maxLines: 1,
|
||||
textAlign: TextAlign.start,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final controller = TextEditingController(
|
||||
text: l10n.publicKey(
|
||||
room
|
||||
.client
|
||||
.userDeviceKeys[user.id]
|
||||
?.masterKey
|
||||
?.publicKey
|
||||
?.beautifiedOneLine ??
|
||||
'???',
|
||||
),
|
||||
);
|
||||
return DialogTextField(
|
||||
controller: controller,
|
||||
textStyle: theme.textTheme.labelSmall,
|
||||
readOnly: true,
|
||||
maxLines: 3,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
AdaptiveDialogAction(
|
||||
autofocus: true,
|
||||
bigButtons: true,
|
||||
onPressed: () {
|
||||
for (final user in users) {
|
||||
room.client.userDeviceKeys[user.id]?.masterKey?.trustOnFirstUse();
|
||||
}
|
||||
Navigator.of(context).pop(_Action.allow);
|
||||
},
|
||||
child: Text(L10n.of(context).continueText),
|
||||
),
|
||||
if (room.isDirectChat)
|
||||
AdaptiveDialogAction(
|
||||
bigButtons: true,
|
||||
onPressed: () => Navigator.of(context).pop(_Action.verification),
|
||||
child: Text(L10n.of(context).interactiveVerification),
|
||||
),
|
||||
AdaptiveDialogAction(
|
||||
bigButtons: true,
|
||||
onPressed: () => Navigator.of(context).pop(_Action.deny),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (action == null) return false;
|
||||
|
||||
switch (action) {
|
||||
case _Action.allow:
|
||||
for (final user in users) {
|
||||
room.client.userDeviceKeys[user.id]?.masterKey?.trustOnFirstUse();
|
||||
}
|
||||
case _Action.deny:
|
||||
return false;
|
||||
case _Action.verification:
|
||||
final req = await room.client.userDeviceKeys[room.directChatMatrixID]
|
||||
?.startVerification();
|
||||
if (req == null) return false;
|
||||
if (!context.mounted) return false;
|
||||
final success = await KeyVerificationDialog(request: req).show(context);
|
||||
return success == true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
enum _Action { allow, deny, verification }
|
||||
103
lib/pages/chat/typing_indicators.dart
Normal file
103
lib/pages/chat/typing_indicators.dart
Normal file
@@ -0,0 +1,103 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/pages/chat/chat.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:tatchat/widgets/typing_animation.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class TypingIndicators extends StatelessWidget {
|
||||
final ChatController controller;
|
||||
const TypingIndicators(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
const avatarSize = Avatar.defaultSize / 2;
|
||||
|
||||
return StreamBuilder<Object>(
|
||||
stream: controller.room.client.onSync.stream.where(
|
||||
(syncUpdate) =>
|
||||
syncUpdate.rooms?.join?[controller.room.id]?.ephemeral?.any(
|
||||
(ephemeral) => ephemeral.type == 'm.typing',
|
||||
) ??
|
||||
false,
|
||||
),
|
||||
builder: (context, _) {
|
||||
final typingUsers = controller.room.typingUsers
|
||||
..removeWhere((u) => u.stateKey == Matrix.of(context).client.userID);
|
||||
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
alignment: Alignment.center,
|
||||
child: AnimatedContainer(
|
||||
constraints: const BoxConstraints(
|
||||
maxWidth: FluffyThemes.maxTimelineWidth,
|
||||
),
|
||||
height: typingUsers.isEmpty ? 0 : avatarSize + 8,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
alignment:
|
||||
controller.timeline!.events.isNotEmpty &&
|
||||
controller.timeline!.events.first.senderId ==
|
||||
Matrix.of(context).client.userID
|
||||
? Alignment.topRight
|
||||
: Alignment.topLeft,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
decoration: const BoxDecoration(),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
alignment: Alignment.center,
|
||||
height: avatarSize,
|
||||
width: Avatar.defaultSize,
|
||||
child: Stack(
|
||||
children: [
|
||||
if (typingUsers.isNotEmpty)
|
||||
Avatar(
|
||||
size: avatarSize,
|
||||
mxContent: typingUsers.first.avatarUrl,
|
||||
name: typingUsers.first.calcDisplayname(),
|
||||
),
|
||||
if (typingUsers.length == 2)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 16),
|
||||
child: Avatar(
|
||||
size: avatarSize,
|
||||
mxContent: typingUsers.length == 2
|
||||
? typingUsers.last.avatarUrl
|
||||
: null,
|
||||
name: typingUsers.length == 2
|
||||
? typingUsers.last.calcDisplayname()
|
||||
: '+${typingUsers.length - 1}',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Material(
|
||||
color: theme.colorScheme.surfaceContainerHigh,
|
||||
borderRadius: const BorderRadius.all(
|
||||
Radius.circular(AppConfig.borderRadius),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: typingUsers.isEmpty ? null : const TypingAnimation(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
76
lib/pages/chat/utd_dialog.dart
Normal file
76
lib/pages/chat/utd_dialog.dart
Normal file
@@ -0,0 +1,76 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat/event_info_dialog.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/adaptive_dialog_action.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class UtdDialog extends StatelessWidget {
|
||||
final Event event;
|
||||
const UtdDialog(this.event, {super.key});
|
||||
|
||||
static Future<void> show(BuildContext context, Event event) async {
|
||||
event.requestKey();
|
||||
final action = await showAdaptiveDialog<_UtdDialogAction>(
|
||||
barrierDismissible: true,
|
||||
context: context,
|
||||
builder: (_) => UtdDialog(event),
|
||||
);
|
||||
if (action == null) return;
|
||||
if (!context.mounted) return;
|
||||
|
||||
switch (action) {
|
||||
case _UtdDialogAction.info:
|
||||
event.showInfoDialog(context);
|
||||
case _UtdDialogAction.redact:
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => event.redactEvent(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog.adaptive(
|
||||
title: Text(L10n.of(context).whyIsThisMessageEncrypted),
|
||||
content: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: 200),
|
||||
child: Scrollbar(
|
||||
thumbVisibility: true,
|
||||
child: SingleChildScrollView(
|
||||
child: SelectableText(
|
||||
event.calcLocalizedBodyFallback(MatrixLocals(L10n.of(context))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
AdaptiveDialogAction(
|
||||
onPressed: () => Navigator.of(context).pop(_UtdDialogAction.info),
|
||||
child: Text(L10n.of(context).messageInfo),
|
||||
),
|
||||
if (event.canRedact)
|
||||
AdaptiveDialogAction(
|
||||
onPressed: () => Navigator.of(context).pop(_UtdDialogAction.redact),
|
||||
child: Text(
|
||||
L10n.of(context).redactMessage,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
AdaptiveDialogAction(
|
||||
onPressed: () => Navigator.of(context).pop(null),
|
||||
child: Text(L10n.of(context).close),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum _UtdDialogAction { info, redact }
|
||||
23
lib/pages/chat/utils/web_file_to_x_file.dart
Normal file
23
lib/pages/chat/utils/web_file_to_x_file.dart
Normal file
@@ -0,0 +1,23 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cross_file/cross_file.dart';
|
||||
import 'package:universal_html/universal_html.dart' as web;
|
||||
|
||||
Future<XFile> webToXFile(web.File file) async {
|
||||
final reader = web.FileReader();
|
||||
reader.readAsArrayBuffer(file);
|
||||
await reader.onLoad.first;
|
||||
|
||||
return XFile(
|
||||
file.relativePath ?? file.name,
|
||||
name: file.name,
|
||||
mimeType: file.type,
|
||||
bytes: reader.result as Uint8List,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_access_settings/chat_access_settings_page.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_modal_action_popup.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_text_input_dialog.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart' hide Visibility;
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatAccessSettings extends StatefulWidget {
|
||||
final String roomId;
|
||||
const ChatAccessSettings({required this.roomId, super.key});
|
||||
|
||||
@override
|
||||
State<ChatAccessSettings> createState() => ChatAccessSettingsController();
|
||||
}
|
||||
|
||||
class ChatAccessSettingsController extends State<ChatAccessSettings> {
|
||||
bool joinRulesLoading = false;
|
||||
bool visibilityLoading = false;
|
||||
bool historyVisibilityLoading = false;
|
||||
bool guestAccessLoading = false;
|
||||
Room get room => Matrix.of(context).client.getRoomById(widget.roomId)!;
|
||||
Set<Room> get knownSpaceParents => {
|
||||
...room.client.rooms.where(
|
||||
(space) =>
|
||||
space.isSpace &&
|
||||
space.spaceChildren.any((child) => child.roomId == room.id),
|
||||
),
|
||||
...room.spaceParents
|
||||
.map((parent) => room.client.getRoomById(parent.roomId ?? ''))
|
||||
.whereType<Room>(),
|
||||
};
|
||||
|
||||
String get roomVersion =>
|
||||
room
|
||||
.getState(EventTypes.RoomCreate)!
|
||||
.content
|
||||
.tryGet<String>('room_version') ??
|
||||
'Unknown';
|
||||
|
||||
/// Calculates which join rules are available based on the information on
|
||||
/// https://spec.matrix.org/v1.11/rooms/#feature-matrix
|
||||
List<JoinRules> get availableJoinRules {
|
||||
final joinRules = Set<JoinRules>.from(JoinRules.values);
|
||||
|
||||
final roomVersionInt = int.tryParse(roomVersion);
|
||||
|
||||
// Knock is only supported for rooms up from version 7:
|
||||
if (roomVersionInt != null && roomVersionInt <= 6) {
|
||||
joinRules.remove(JoinRules.knock);
|
||||
}
|
||||
|
||||
// Restricted is only supported for rooms up from version 8:
|
||||
if (roomVersionInt != null && roomVersionInt <= 7) {
|
||||
joinRules.remove(JoinRules.restricted);
|
||||
}
|
||||
|
||||
// Knock-Restricted is only supported for rooms up from version 10:
|
||||
if (roomVersionInt != null && roomVersionInt <= 9) {
|
||||
joinRules.remove(JoinRules.knockRestricted);
|
||||
}
|
||||
|
||||
if (knownSpaceParents.isEmpty) {
|
||||
joinRules.remove(JoinRules.restricted);
|
||||
joinRules.remove(JoinRules.knockRestricted);
|
||||
}
|
||||
|
||||
// If an unsupported join rule is the current join rule, display it:
|
||||
final currentJoinRule = room.joinRules;
|
||||
if (currentJoinRule != null) joinRules.add(currentJoinRule);
|
||||
|
||||
return joinRules.toList();
|
||||
}
|
||||
|
||||
Future<void> setJoinRule(JoinRules? newJoinRules) async {
|
||||
if (newJoinRules == null) return;
|
||||
setState(() {
|
||||
joinRulesLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await room.setJoinRules(
|
||||
newJoinRules,
|
||||
allowConditionRoomIds:
|
||||
{
|
||||
JoinRules.restricted,
|
||||
JoinRules.knockRestricted,
|
||||
}.contains(newJoinRules)
|
||||
? knownSpaceParents.map((parent) => parent.id).toList()
|
||||
: null,
|
||||
);
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to change join rules', e, s);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
joinRulesLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setHistoryVisibility(
|
||||
HistoryVisibility? historyVisibility,
|
||||
) async {
|
||||
if (historyVisibility == null) return;
|
||||
setState(() {
|
||||
historyVisibilityLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await room.setHistoryVisibility(historyVisibility);
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to change history visibility', e, s);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
historyVisibilityLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setGuestAccess(GuestAccess? guestAccess) async {
|
||||
if (guestAccess == null) return;
|
||||
setState(() {
|
||||
guestAccessLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await room.setGuestAccess(guestAccess);
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to change guest access', e, s);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
guestAccessLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateRoomAction() async {
|
||||
final l10n = L10n.of(context);
|
||||
final roomVersion = room
|
||||
.getState(EventTypes.RoomCreate)!
|
||||
.content
|
||||
.tryGet<String>('room_version');
|
||||
final capabilitiesResult = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.client.getCapabilities(),
|
||||
);
|
||||
final capabilities = capabilitiesResult.result;
|
||||
if (capabilities == null) return;
|
||||
if (!mounted) return;
|
||||
final newVersion = await showModalActionPopup<String>(
|
||||
context: context,
|
||||
title: l10n.replaceRoomWithNewerVersion,
|
||||
cancelLabel: l10n.cancel,
|
||||
actions: capabilities.mRoomVersions!.available.entries
|
||||
.where((r) => r.key != roomVersion)
|
||||
.map(
|
||||
(version) => AdaptiveModalAction(
|
||||
value: version.key,
|
||||
label:
|
||||
'${version.key} (${version.value.toString().split('.').last})',
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
if (newVersion == null) return;
|
||||
if (!mounted) return;
|
||||
final confirmUpgrade = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
okLabel: l10n.yes,
|
||||
cancelLabel: l10n.cancel,
|
||||
title: l10n.areYouSure,
|
||||
message: l10n.roomUpgradeDescription,
|
||||
isDestructive: true,
|
||||
);
|
||||
if (confirmUpgrade == OkCancelResult.cancel) {
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
final result = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
futureWithProgress: (onProgress) async {
|
||||
final newRoomId = await room.client.upgradeRoom(room.id, newVersion);
|
||||
var newRoom = room.client.getRoomById(newRoomId);
|
||||
while (newRoom == null) {
|
||||
await room.client.onSync.stream.first;
|
||||
newRoom = room.client.getRoomById(newRoomId);
|
||||
}
|
||||
|
||||
if ({
|
||||
JoinRules.invite,
|
||||
JoinRules.knock,
|
||||
JoinRules.knockRestricted,
|
||||
}.contains(room.joinRules)) {
|
||||
final users = await room.requestParticipants([
|
||||
Membership.join,
|
||||
Membership.invite,
|
||||
]);
|
||||
users.removeWhere((user) => user.id == room.client.userID);
|
||||
for (final (i, user) in users.indexed) {
|
||||
try {
|
||||
Logs().v('Inviting...', user.id);
|
||||
await newRoom.invite(user.id);
|
||||
onProgress(i / users.length);
|
||||
} on MatrixException catch (e) {
|
||||
final retryAfterMs = e.retryAfterMs;
|
||||
if (e.error != MatrixError.M_LIMIT_EXCEEDED ||
|
||||
retryAfterMs == null) {
|
||||
rethrow;
|
||||
}
|
||||
Logs().d('Limit exceeded. Retry after $retryAfterMs');
|
||||
await Future.delayed(Duration(milliseconds: retryAfterMs));
|
||||
await newRoom.invite(user.id);
|
||||
onProgress(i / users.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
if (result.error != null) return;
|
||||
if (!mounted) return;
|
||||
context.go('/rooms/${room.id}');
|
||||
}
|
||||
|
||||
Future<void> addAlias() async {
|
||||
final l10n = L10n.of(context);
|
||||
final domain = room.client.userID?.domain;
|
||||
if (domain == null) {
|
||||
throw Exception('userID or domain is null! This should never happen.');
|
||||
}
|
||||
|
||||
final input = await showTextInputDialog(
|
||||
context: context,
|
||||
title: l10n.editRoomAliases,
|
||||
prefixText: '#',
|
||||
suffixText: domain,
|
||||
hintText: l10n.alias,
|
||||
);
|
||||
if (!mounted) return;
|
||||
final aliasLocalpart = input?.trim();
|
||||
if (aliasLocalpart == null || aliasLocalpart.isEmpty) return;
|
||||
final alias = '#$aliasLocalpart:$domain';
|
||||
|
||||
final result = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.client.setRoomAlias(alias, room.id),
|
||||
);
|
||||
if (result.error != null) return;
|
||||
if (!mounted) return;
|
||||
setState(() {});
|
||||
|
||||
if (!room.canChangeStateEvent(EventTypes.RoomCanonicalAlias)) return;
|
||||
|
||||
final canonicalAliasConsent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: l10n.setAsCanonicalAlias,
|
||||
message: alias,
|
||||
okLabel: l10n.yes,
|
||||
cancelLabel: l10n.no,
|
||||
);
|
||||
if (!mounted) return;
|
||||
|
||||
final altAliases =
|
||||
room
|
||||
.getState(EventTypes.RoomCanonicalAlias)
|
||||
?.content
|
||||
.tryGetList<String>('alt_aliases')
|
||||
?.toSet() ??
|
||||
{};
|
||||
if (room.canonicalAlias.isNotEmpty) altAliases.add(room.canonicalAlias);
|
||||
altAliases.add(alias);
|
||||
if (canonicalAliasConsent == OkCancelResult.ok) {
|
||||
altAliases.remove(alias);
|
||||
} else {
|
||||
altAliases.remove(room.canonicalAlias);
|
||||
}
|
||||
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.client
|
||||
.setRoomStateWithKey(room.id, EventTypes.RoomCanonicalAlias, '', {
|
||||
'alias': canonicalAliasConsent == OkCancelResult.ok
|
||||
? alias
|
||||
: room.canonicalAlias,
|
||||
if (altAliases.isNotEmpty) 'alt_aliases': altAliases.toList(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> deleteAlias(String alias) async {
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.client.deleteRoomAlias(alias),
|
||||
);
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> setChatVisibilityOnDirectory(bool? visibility) async {
|
||||
if (visibility == null) return;
|
||||
setState(() {
|
||||
visibilityLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await room.client.setRoomVisibilityOnDirectory(
|
||||
room.id,
|
||||
visibility: visibility == true ? Visibility.public : Visibility.private,
|
||||
);
|
||||
setState(() {});
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to change visibility', e, s);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
visibilityLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ChatAccessSettingsPageView(this);
|
||||
}
|
||||
}
|
||||
318
lib/pages/chat_access_settings/chat_access_settings_page.dart
Normal file
318
lib/pages/chat_access_settings/chat_access_settings_page.dart
Normal file
@@ -0,0 +1,318 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_access_settings/chat_access_settings_controller.dart';
|
||||
import 'package:tatchat/utils/tatu_share.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/widgets/layouts/max_width_body.dart';
|
||||
import 'package:material_ui/material_ui.dart' hide Visibility;
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatAccessSettingsPageView extends StatelessWidget {
|
||||
final ChatAccessSettingsController controller;
|
||||
const ChatAccessSettingsPageView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final room = controller.room;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: const Center(child: BackButton()),
|
||||
title: Text(L10n.of(context).accessAndVisibility),
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
child: StreamBuilder<Object>(
|
||||
stream: room.client.onRoomState.stream.where(
|
||||
(update) => update.roomId == controller.room.id,
|
||||
),
|
||||
builder: (context, snapshot) {
|
||||
final canonicalAlias = room.canonicalAlias;
|
||||
final altAliases =
|
||||
room
|
||||
.getState(EventTypes.RoomCanonicalAlias)
|
||||
?.content
|
||||
.tryGetList<String>('alt_aliases') ??
|
||||
[];
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).visibilityOfTheChatHistory,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.secondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
RadioGroup<HistoryVisibility>(
|
||||
groupValue: room.historyVisibility,
|
||||
onChanged:
|
||||
controller.historyVisibilityLoading ||
|
||||
!room.canChangeHistoryVisibility
|
||||
? (_) {}
|
||||
: controller.setHistoryVisibility,
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
for (final historyVisibility in HistoryVisibility.values)
|
||||
RadioListTile<HistoryVisibility>.adaptive(
|
||||
title: Text(
|
||||
historyVisibility.getLocalizedString(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
),
|
||||
),
|
||||
value: historyVisibility,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Divider(color: theme.dividerColor),
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).whoIsAllowedToJoinThisGroup,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.secondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
RadioGroup(
|
||||
groupValue: room.joinRules,
|
||||
onChanged: controller.setJoinRule,
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
for (final joinRule in controller.availableJoinRules)
|
||||
if (joinRule != JoinRules.private)
|
||||
RadioListTile<JoinRules>.adaptive(
|
||||
enabled:
|
||||
!controller.joinRulesLoading &&
|
||||
room.canChangeJoinRules,
|
||||
title: Text(
|
||||
joinRule.localizedString(
|
||||
L10n.of(context),
|
||||
controller.knownSpaceParents,
|
||||
),
|
||||
),
|
||||
value: joinRule,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Divider(color: theme.dividerColor),
|
||||
if ({
|
||||
JoinRules.public,
|
||||
JoinRules.knock,
|
||||
}.contains(room.joinRules)) ...[
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).areGuestsAllowedToJoin,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.secondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
RadioGroup(
|
||||
groupValue: room.guestAccess,
|
||||
onChanged: controller.setGuestAccess,
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
for (final guestAccess in GuestAccess.values)
|
||||
RadioListTile<GuestAccess>.adaptive(
|
||||
enabled:
|
||||
!controller.guestAccessLoading &&
|
||||
room.canChangeGuestAccess,
|
||||
title: Text(
|
||||
guestAccess.getLocalizedString(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
),
|
||||
),
|
||||
value: guestAccess,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Divider(color: theme.dividerColor),
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).publicChatAddresses,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.secondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.add_outlined),
|
||||
tooltip: L10n.of(context).createNewAddress,
|
||||
onPressed: controller.addAlias,
|
||||
),
|
||||
),
|
||||
if (canonicalAlias.isNotEmpty)
|
||||
_AliasListTile(
|
||||
alias: canonicalAlias,
|
||||
onDelete:
|
||||
room.canChangeStateEvent(
|
||||
EventTypes.RoomCanonicalAlias,
|
||||
)
|
||||
? () => controller.deleteAlias(canonicalAlias)
|
||||
: null,
|
||||
isCanonicalAlias: true,
|
||||
),
|
||||
for (final alias in altAliases)
|
||||
_AliasListTile(
|
||||
alias: alias,
|
||||
onDelete:
|
||||
room.canChangeStateEvent(
|
||||
EventTypes.RoomCanonicalAlias,
|
||||
)
|
||||
? () => controller.deleteAlias(alias)
|
||||
: null,
|
||||
),
|
||||
FutureBuilder(
|
||||
future: room.client.getLocalAliases(room.id),
|
||||
builder: (context, snapshot) {
|
||||
final localAddresses = snapshot.data;
|
||||
if (localAddresses == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
localAddresses.remove(room.canonicalAlias);
|
||||
localAddresses.removeWhere(altAliases.contains);
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
children: localAddresses
|
||||
.map(
|
||||
(alias) => _AliasListTile(
|
||||
alias: alias,
|
||||
published: false,
|
||||
onDelete: () => controller.deleteAlias(alias),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
Divider(color: theme.dividerColor),
|
||||
FutureBuilder(
|
||||
future: room.client.getRoomVisibilityOnDirectory(room.id),
|
||||
builder: (context, snapshot) => SwitchListTile.adaptive(
|
||||
value: snapshot.data == Visibility.public,
|
||||
title: Text(
|
||||
L10n.of(context).chatCanBeDiscoveredViaSearchOnServer(
|
||||
room.client.userID!.domain!,
|
||||
),
|
||||
),
|
||||
onChanged: controller.setChatVisibilityOnDirectory,
|
||||
),
|
||||
),
|
||||
],
|
||||
ListTile(
|
||||
title: Text(L10n.of(context).globalChatId),
|
||||
subtitle: SelectableText(room.id),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.copy_outlined),
|
||||
onPressed: () => TatuShare.share(room.id, context),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
title: Text(L10n.of(context).roomVersion),
|
||||
subtitle: SelectableText(
|
||||
room
|
||||
.getState(EventTypes.RoomCreate)!
|
||||
.content
|
||||
.tryGet<String>('room_version') ??
|
||||
'Unknown',
|
||||
),
|
||||
trailing: room.canSendEvent(EventTypes.RoomTombstone)
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.upgrade_outlined),
|
||||
onPressed: controller.updateRoomAction,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AliasListTile extends StatelessWidget {
|
||||
const _AliasListTile({
|
||||
required this.alias,
|
||||
required this.onDelete,
|
||||
this.isCanonicalAlias = false,
|
||||
this.published = true,
|
||||
});
|
||||
|
||||
final String alias;
|
||||
final void Function()? onDelete;
|
||||
final bool isCanonicalAlias;
|
||||
final bool published;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return ListTile(
|
||||
leading: isCanonicalAlias
|
||||
? const Icon(Icons.star)
|
||||
: const Icon(Icons.link_outlined),
|
||||
title: InkWell(
|
||||
onTap: () => TatuShare.share('https://matrix.to/#/$alias', context),
|
||||
child: SelectableText(
|
||||
alias,
|
||||
style: TextStyle(
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: theme.colorScheme.primary,
|
||||
color: theme.colorScheme.primary,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
),
|
||||
trailing: onDelete != null
|
||||
? IconButton(
|
||||
color: theme.colorScheme.error,
|
||||
icon: const Icon(Icons.delete_outlined),
|
||||
onPressed: onDelete,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension JoinRulesDisplayString on JoinRules {
|
||||
String localizedString(L10n l10n, Set<Room> spaceParents) {
|
||||
switch (this) {
|
||||
case JoinRules.public:
|
||||
return l10n.anyoneCanJoin;
|
||||
case JoinRules.invite:
|
||||
return l10n.invitedUsersOnly;
|
||||
case JoinRules.knock:
|
||||
return l10n.usersMustKnock;
|
||||
case JoinRules.private:
|
||||
return l10n.noOneCanJoin;
|
||||
case JoinRules.restricted:
|
||||
return l10n.spaceMemberOf(
|
||||
spaceParents
|
||||
.map((space) => space.getLocalizedDisplayname(MatrixLocals(l10n)))
|
||||
.join(', '),
|
||||
);
|
||||
case JoinRules.knockRestricted:
|
||||
return l10n.spaceMemberOfCanKnock(
|
||||
spaceParents
|
||||
.map((space) => space.getLocalizedDisplayname(MatrixLocals(l10n)))
|
||||
.join(', '),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
173
lib/pages/chat_details/chat_details.dart
Normal file
173
lib/pages/chat_details/chat_details.dart
Normal file
@@ -0,0 +1,173 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_details/chat_details_view.dart';
|
||||
import 'package:tatchat/pages/settings/settings.dart';
|
||||
import 'package:tatchat/utils/file_selector.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_modal_action_popup.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_text_input_dialog.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatDetails extends StatefulWidget {
|
||||
final String roomId;
|
||||
final Widget? embeddedCloseButton;
|
||||
|
||||
const ChatDetails({
|
||||
super.key,
|
||||
required this.roomId,
|
||||
this.embeddedCloseButton,
|
||||
});
|
||||
|
||||
@override
|
||||
ChatDetailsController createState() => ChatDetailsController();
|
||||
}
|
||||
|
||||
class ChatDetailsController extends State<ChatDetails> {
|
||||
bool displaySettings = false;
|
||||
|
||||
void toggleDisplaySettings() =>
|
||||
setState(() => displaySettings = !displaySettings);
|
||||
|
||||
String? get roomId => widget.roomId;
|
||||
|
||||
Future<void> setDisplaynameAction() async {
|
||||
final l10n = L10n.of(context);
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
final room = Matrix.of(context).client.getRoomById(roomId!)!;
|
||||
final input = await showTextInputDialog(
|
||||
context: context,
|
||||
title: l10n.changeTheNameOfTheGroup,
|
||||
okLabel: l10n.ok,
|
||||
cancelLabel: l10n.cancel,
|
||||
initialText: room.getLocalizedDisplayname(MatrixLocals(l10n)),
|
||||
);
|
||||
if (input == null) return;
|
||||
if (!mounted) return;
|
||||
final success = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.setName(input),
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (success.error == null) {
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.displaynameHasBeenChanged)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setTopicAction() async {
|
||||
final l10n = L10n.of(context);
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
final room = Matrix.of(context).client.getRoomById(roomId!)!;
|
||||
final input = await showTextInputDialog(
|
||||
context: context,
|
||||
title: l10n.setChatDescription,
|
||||
okLabel: l10n.ok,
|
||||
cancelLabel: l10n.cancel,
|
||||
hintText: l10n.noChatDescriptionYet,
|
||||
initialText: room.topic,
|
||||
minLines: 4,
|
||||
maxLines: 8,
|
||||
);
|
||||
if (input == null) return;
|
||||
if (!mounted) return;
|
||||
final success = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.setDescription(input),
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (success.error == null) {
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.chatDescriptionHasBeenChanged)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setAvatarAction() async {
|
||||
final l10n = L10n.of(context);
|
||||
final room = Matrix.of(context).client.getRoomById(roomId!);
|
||||
final actions = [
|
||||
if (PlatformInfos.isMobile)
|
||||
AdaptiveModalAction(
|
||||
value: AvatarAction.camera,
|
||||
label: l10n.openCamera,
|
||||
isDefaultAction: true,
|
||||
icon: const Icon(Icons.camera_alt_outlined),
|
||||
),
|
||||
AdaptiveModalAction(
|
||||
value: AvatarAction.file,
|
||||
label: l10n.openGallery,
|
||||
icon: const Icon(Icons.photo_outlined),
|
||||
),
|
||||
if (room?.avatar != null)
|
||||
AdaptiveModalAction(
|
||||
value: AvatarAction.remove,
|
||||
label: l10n.delete,
|
||||
isDestructive: true,
|
||||
icon: const Icon(Icons.delete_outlined),
|
||||
),
|
||||
];
|
||||
final action = actions.length == 1
|
||||
? actions.single.value
|
||||
: await showModalActionPopup<AvatarAction>(
|
||||
context: context,
|
||||
title: l10n.editRoomAvatar,
|
||||
cancelLabel: l10n.cancel,
|
||||
actions: actions,
|
||||
);
|
||||
if (action == null) return;
|
||||
if (!mounted) return;
|
||||
if (action == AvatarAction.remove) {
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room!.setAvatar(null),
|
||||
);
|
||||
return;
|
||||
}
|
||||
MatrixFile file;
|
||||
if (PlatformInfos.isMobile) {
|
||||
final result = await ImagePicker().pickImage(
|
||||
source: action == AvatarAction.camera
|
||||
? ImageSource.camera
|
||||
: ImageSource.gallery,
|
||||
imageQuality: 50,
|
||||
);
|
||||
if (result == null) return;
|
||||
file = MatrixFile(bytes: await result.readAsBytes(), name: result.path);
|
||||
} else {
|
||||
if (!mounted) return;
|
||||
final picked = await selectFiles(
|
||||
context,
|
||||
allowMultiple: false,
|
||||
type: FileType.image,
|
||||
);
|
||||
final pickedFile = picked.firstOrNull;
|
||||
if (pickedFile == null) return;
|
||||
file = MatrixFile(
|
||||
bytes: await pickedFile.readAsBytes(),
|
||||
name: pickedFile.name,
|
||||
);
|
||||
}
|
||||
if (!mounted) return;
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room!.setAvatar(file),
|
||||
);
|
||||
}
|
||||
|
||||
static const fixedWidth = 360.0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ChatDetailsView(this);
|
||||
}
|
||||
418
lib/pages/chat_details/chat_details_view.dart
Normal file
418
lib/pages/chat_details/chat_details_view.dart
Normal file
@@ -0,0 +1,418 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_details/chat_details.dart';
|
||||
import 'package:tatchat/pages/chat_details/participant_list_item.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/utils/verified_room_extension.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/chat_settings_popup_menu.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/layouts/max_width_body.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../utils/url_launcher.dart';
|
||||
import '../../widgets/mxc_image_viewer.dart';
|
||||
import '../../widgets/qr_code_viewer.dart';
|
||||
|
||||
class ChatDetailsView extends StatelessWidget {
|
||||
final ChatDetailsController controller;
|
||||
|
||||
const ChatDetailsView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final room = Matrix.of(context).client.getRoomById(controller.roomId!);
|
||||
if (room == null) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(L10n.of(context).oopsSomethingWentWrong)),
|
||||
body: Center(
|
||||
child: Text(L10n.of(context).youAreNoLongerParticipatingInThisChat),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final directChatMatrixID = room.directChatMatrixID;
|
||||
final roomAvatar = room.avatar;
|
||||
|
||||
return StreamBuilder(
|
||||
stream: room.client.onRoomState.stream.where(
|
||||
(update) => update.roomId == room.id,
|
||||
),
|
||||
builder: (context, snapshot) {
|
||||
var members = room.getParticipants().toList()
|
||||
..sort((b, a) => a.powerLevel.level.compareTo(b.powerLevel.level));
|
||||
members = members.take(10).toList();
|
||||
final actualMembersCount =
|
||||
(room.summary.mInvitedMemberCount ?? 0) +
|
||||
(room.summary.mJoinedMemberCount ?? 0);
|
||||
final canRequestMoreMembers = members.length < actualMembersCount;
|
||||
final iconColor = theme.textTheme.bodyLarge!.color;
|
||||
final displayname = room.getLocalizedDisplayname(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
);
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading:
|
||||
controller.widget.embeddedCloseButton ??
|
||||
const Center(child: BackButton()),
|
||||
elevation: theme.appBarTheme.elevation,
|
||||
actions: <Widget>[
|
||||
if (room.canonicalAlias.isNotEmpty)
|
||||
IconButton(
|
||||
tooltip: L10n.of(context).share,
|
||||
icon: const Icon(Icons.qr_code_rounded),
|
||||
onPressed: () =>
|
||||
showQrCodeViewer(context, room.canonicalAlias),
|
||||
)
|
||||
else if (directChatMatrixID != null)
|
||||
IconButton(
|
||||
tooltip: L10n.of(context).share,
|
||||
icon: const Icon(Icons.qr_code_rounded),
|
||||
onPressed: () =>
|
||||
showQrCodeViewer(context, directChatMatrixID),
|
||||
),
|
||||
if (controller.widget.embeddedCloseButton == null)
|
||||
ChatSettingsPopupMenu(room, false),
|
||||
],
|
||||
title: Text(L10n.of(context).chatDetails),
|
||||
backgroundColor: theme.appBarTheme.backgroundColor,
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
child: ListView.builder(
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
shrinkWrap: true,
|
||||
itemCount: members.length + 1 + (canRequestMoreMembers ? 1 : 0),
|
||||
itemBuilder: (BuildContext context, int i) => i == 0
|
||||
? Column(
|
||||
crossAxisAlignment: .stretch,
|
||||
children: <Widget>[
|
||||
Center(
|
||||
child: Stack(
|
||||
children: [
|
||||
Hero(
|
||||
tag:
|
||||
controller.widget.embeddedCloseButton !=
|
||||
null
|
||||
? 'embedded_content_banner'
|
||||
: 'content_banner',
|
||||
child: Avatar(
|
||||
mxContent: room.avatar,
|
||||
name: displayname,
|
||||
size: Avatar.defaultSize * 2.5,
|
||||
onTap: roomAvatar != null
|
||||
? () => showDialog(
|
||||
context: context,
|
||||
builder: (_) =>
|
||||
MxcImageViewer(roomAvatar),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
if (!room.isDirectChat &&
|
||||
room.canChangeStateEvent(
|
||||
EventTypes.RoomAvatar,
|
||||
))
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
child: FloatingActionButton.small(
|
||||
onPressed: controller.setAvatarAction,
|
||||
heroTag: null,
|
||||
child: const Icon(
|
||||
Icons.camera_alt_outlined,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Center(
|
||||
child: TextButton.icon(
|
||||
onPressed:
|
||||
room.isDirectChat ||
|
||||
!room.canChangeStateEvent(
|
||||
EventTypes.RoomName,
|
||||
)
|
||||
? null
|
||||
: controller.setDisplaynameAction,
|
||||
icon:
|
||||
room.isDirectChat ||
|
||||
!room.canChangeStateEvent(
|
||||
EventTypes.RoomName,
|
||||
)
|
||||
? null
|
||||
: Icon(Icons.edit_outlined, size: 16),
|
||||
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: theme.colorScheme.onSurface,
|
||||
iconColor: theme.colorScheme.onSurface,
|
||||
disabledForegroundColor:
|
||||
theme.colorScheme.onSurface,
|
||||
),
|
||||
label: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 4,
|
||||
children: [
|
||||
if (room.allUsersVerified)
|
||||
Icon(
|
||||
Icons.verified,
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary,
|
||||
size: 18,
|
||||
),
|
||||
Text(
|
||||
displayname,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
StreamBuilder(
|
||||
stream: room.client.onSync.stream.where(
|
||||
(s) =>
|
||||
s.accountData?.any(
|
||||
(data) => data.type == 'm.push_rules',
|
||||
) ??
|
||||
false,
|
||||
),
|
||||
builder: (context, _) => Wrap(
|
||||
alignment: .center,
|
||||
spacing: 16,
|
||||
runSpacing: 16,
|
||||
children: [
|
||||
_MainChatDetailsButton(
|
||||
onPressed: () =>
|
||||
context.go('/rooms/${room.id}/search'),
|
||||
label: L10n.of(context).search,
|
||||
icon: Icons.search,
|
||||
),
|
||||
_MainChatDetailsButton(
|
||||
onPressed: () => context.push(
|
||||
'/rooms/${room.id}/details/emotes',
|
||||
),
|
||||
label: L10n.of(context).stickers,
|
||||
icon: Icons.emoji_emotions_outlined,
|
||||
),
|
||||
if (room.pushRuleState == PushRuleState.notify)
|
||||
_MainChatDetailsButton(
|
||||
onPressed: () => showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.setPushRuleState(
|
||||
PushRuleState.mentionsOnly,
|
||||
),
|
||||
),
|
||||
label: L10n.of(context).mute,
|
||||
icon: Icons.notifications_on_outlined,
|
||||
)
|
||||
else
|
||||
_MainChatDetailsButton(
|
||||
onPressed: () => showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.setPushRuleState(
|
||||
PushRuleState.notify,
|
||||
),
|
||||
),
|
||||
label: L10n.of(context).unmuteChat,
|
||||
icon: Icons.notifications_off_outlined,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (room.canChangeStateEvent(EventTypes.RoomTopic) ||
|
||||
room.topic.isNotEmpty) ...[
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).chatDescription,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.secondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
trailing:
|
||||
room.canChangeStateEvent(EventTypes.RoomTopic)
|
||||
? IconButton(
|
||||
onPressed: controller.setTopicAction,
|
||||
tooltip: L10n.of(
|
||||
context,
|
||||
).setChatDescription,
|
||||
icon: const Icon(Icons.edit_outlined),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
),
|
||||
child: SelectableLinkify(
|
||||
text: room.topic.isEmpty
|
||||
? L10n.of(context).noChatDescriptionYet
|
||||
: room.topic,
|
||||
textScaleFactor: MediaQuery.textScalerOf(
|
||||
context,
|
||||
).scale(1),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: const TextStyle(
|
||||
color: Colors.blueAccent,
|
||||
decorationColor: Colors.blueAccent,
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontStyle: room.topic.isEmpty
|
||||
? FontStyle.italic
|
||||
: FontStyle.normal,
|
||||
color: theme.textTheme.bodyMedium!.color,
|
||||
decorationColor:
|
||||
theme.textTheme.bodyMedium!.color,
|
||||
),
|
||||
onOpen: (url) =>
|
||||
UrlLauncher(context, url.url).launchUrl(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
if (!room.isDirectChat) ...[
|
||||
Divider(color: theme.dividerColor),
|
||||
ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.surfaceContainer,
|
||||
foregroundColor: iconColor,
|
||||
child: const Icon(
|
||||
Icons.admin_panel_settings_outlined,
|
||||
),
|
||||
),
|
||||
title: Text(L10n.of(context).accessAndVisibility),
|
||||
subtitle: Text(
|
||||
L10n.of(context).accessAndVisibilityDescription,
|
||||
),
|
||||
onTap: () => context.push(
|
||||
'/rooms/${room.id}/details/access',
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right_outlined),
|
||||
),
|
||||
ListTile(
|
||||
title: Text(L10n.of(context).chatPermissions),
|
||||
subtitle: Text(
|
||||
L10n.of(context).whoCanPerformWhichAction,
|
||||
),
|
||||
leading: CircleAvatar(
|
||||
backgroundColor:
|
||||
theme.colorScheme.surfaceContainer,
|
||||
foregroundColor: iconColor,
|
||||
child: const Icon(Icons.tune_outlined),
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right_outlined),
|
||||
onTap: () => context.push(
|
||||
'/rooms/${room.id}/details/permissions',
|
||||
),
|
||||
),
|
||||
],
|
||||
Divider(color: theme.dividerColor),
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).countParticipants(actualMembersCount),
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.secondary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
trailing: !room.isDirectChat && room.canInvite
|
||||
? TextButton.icon(
|
||||
icon: Icon(Icons.add),
|
||||
label: Text(L10n.of(context).invite),
|
||||
onPressed: () =>
|
||||
context.go('/rooms/${room.id}/invite'),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
)
|
||||
: i < members.length + 1
|
||||
? ParticipantListItem(members[i - 1])
|
||||
: ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).loadCountMoreParticipants(
|
||||
(actualMembersCount - members.length),
|
||||
),
|
||||
),
|
||||
onTap: () => context.push(
|
||||
'/rooms/${controller.roomId!}/details/members',
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right_outlined),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MainChatDetailsButton extends StatelessWidget {
|
||||
final VoidCallback onPressed;
|
||||
final String label;
|
||||
final IconData icon;
|
||||
|
||||
const _MainChatDetailsButton({
|
||||
required this.onPressed,
|
||||
required this.label,
|
||||
required this.icon,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Material(
|
||||
color: theme.colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
child: InkWell(
|
||||
onTap: onPressed,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: .center,
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Icon(icon, color: theme.colorScheme.secondary),
|
||||
SizedBox(
|
||||
width: 64,
|
||||
child: Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
textAlign: .center,
|
||||
style: TextStyle(color: theme.colorScheme.secondary),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
114
lib/pages/chat_details/participant_list_item.dart
Normal file
114
lib/pages/chat_details/participant_list_item.dart
Normal file
@@ -0,0 +1,114 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/widgets/member_actions_popup_menu_button.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../widgets/avatar.dart';
|
||||
|
||||
class ParticipantListItem extends StatelessWidget {
|
||||
final User user;
|
||||
|
||||
const ParticipantListItem(this.user, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final membershipBatch = switch (user.membership) {
|
||||
Membership.ban => L10n.of(context).banned,
|
||||
Membership.invite => L10n.of(context).invited,
|
||||
Membership.join => null,
|
||||
Membership.knock => L10n.of(context).knocking,
|
||||
Membership.leave => L10n.of(context).leftTheChat,
|
||||
};
|
||||
|
||||
final permissionBatch = switch (user.powerLevel.role) {
|
||||
PowerLevelRole.user => null,
|
||||
PowerLevelRole.moderator => L10n.of(context).moderator,
|
||||
PowerLevelRole.admin => L10n.of(context).admin,
|
||||
PowerLevelRole.owner => L10n.of(context).owner,
|
||||
};
|
||||
|
||||
final isAdminOrOwner =
|
||||
user.powerLevel.role == PowerLevelRole.admin ||
|
||||
user.powerLevel.role == PowerLevelRole.owner;
|
||||
|
||||
return ListTile(
|
||||
onTap: () => showMemberActionsPopupMenu(context: context, user: user),
|
||||
title: Row(
|
||||
children: <Widget>[
|
||||
if (user.room.client.userDeviceKeys[user.id]?.masterKey?.verified ==
|
||||
true)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 2.0),
|
||||
child: Icon(
|
||||
Icons.verified,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
user.calcDisplayname(),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
if (permissionBatch != null)
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: isAdminOrOwner
|
||||
? theme.colorScheme.tertiary
|
||||
: theme.colorScheme.tertiaryContainer,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
),
|
||||
child: Text(
|
||||
permissionBatch,
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: isAdminOrOwner
|
||||
? theme.colorScheme.onTertiary
|
||||
: theme.colorScheme.onTertiaryContainer,
|
||||
),
|
||||
),
|
||||
),
|
||||
membershipBatch == null
|
||||
? const SizedBox.shrink()
|
||||
: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 4,
|
||||
horizontal: 8,
|
||||
),
|
||||
margin: const EdgeInsets.symmetric(horizontal: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.secondaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
membershipBatch,
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: theme.colorScheme.onSecondaryContainer,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
subtitle: Text(user.id, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
leading: Opacity(
|
||||
opacity: user.membership == Membership.join ? 1 : 0.5,
|
||||
child: Avatar(
|
||||
mxContent: user.avatarUrl,
|
||||
name: user.calcDisplayname(),
|
||||
presenceUserId: user.stateKey,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
121
lib/pages/chat_encryption_settings/chat_encryption_settings.dart
Normal file
121
lib/pages/chat_encryption_settings/chat_encryption_settings.dart
Normal file
@@ -0,0 +1,121 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_encryption_settings/chat_encryption_settings_view.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/encryption.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../key_verification/key_verification_dialog.dart';
|
||||
|
||||
class ChatEncryptionSettings extends StatefulWidget {
|
||||
const ChatEncryptionSettings({super.key});
|
||||
|
||||
@override
|
||||
ChatEncryptionSettingsController createState() =>
|
||||
ChatEncryptionSettingsController();
|
||||
}
|
||||
|
||||
class ChatEncryptionSettingsController extends State<ChatEncryptionSettings> {
|
||||
String? get roomId => GoRouterState.of(context).pathParameters['roomid'];
|
||||
|
||||
Room get room => Matrix.of(context).client.getRoomById(roomId!)!;
|
||||
|
||||
Future<void> unblock(DeviceKeys key) async {
|
||||
if (key.blocked) {
|
||||
await key.setBlocked(false);
|
||||
}
|
||||
}
|
||||
|
||||
String? uncollapsedUserId;
|
||||
|
||||
void uncollapse(String? userId) {
|
||||
setState(() {
|
||||
if (uncollapsedUserId == userId) {
|
||||
uncollapsedUserId = null;
|
||||
} else {
|
||||
uncollapsedUserId = userId;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> enableEncryption(_) async {
|
||||
final l10n = L10n.of(context);
|
||||
if (room.encrypted) {
|
||||
showOkAlertDialog(
|
||||
context: context,
|
||||
title: l10n.sorryThatsNotPossible,
|
||||
message: l10n.disableEncryptionWarning,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (room.joinRules == JoinRules.public) {
|
||||
showOkAlertDialog(
|
||||
context: context,
|
||||
title: l10n.sorryThatsNotPossible,
|
||||
message: l10n.noEncryptionForPublicRooms,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!room.canChangeStateEvent(EventTypes.Encryption)) {
|
||||
showOkAlertDialog(
|
||||
context: context,
|
||||
title: l10n.sorryThatsNotPossible,
|
||||
message: l10n.noPermission,
|
||||
);
|
||||
return;
|
||||
}
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: l10n.areYouSure,
|
||||
message: l10n.enableEncryptionWarning,
|
||||
okLabel: l10n.yes,
|
||||
cancelLabel: l10n.cancel,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!mounted) return;
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.enableEncryption(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> startVerification() async {
|
||||
final l10n = L10n.of(context);
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: l10n.verifyOtherUser,
|
||||
message: l10n.verifyOtherUserDescription,
|
||||
okLabel: l10n.ok,
|
||||
cancelLabel: l10n.cancel,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!mounted) return;
|
||||
final req = await room.client.userDeviceKeys[room.directChatMatrixID]!
|
||||
.startVerification();
|
||||
req.onUpdate = () {
|
||||
if (req.state == KeyVerificationState.done) {
|
||||
setState(() {});
|
||||
}
|
||||
};
|
||||
if (!mounted) return;
|
||||
await KeyVerificationDialog(request: req).show(context);
|
||||
}
|
||||
|
||||
void toggleBlocked(DeviceKeys key) {
|
||||
setState(() {
|
||||
if (!key.blocked && key.verified) key.setVerified(false);
|
||||
key.setBlocked(!key.blocked);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ChatEncryptionSettingsView(this);
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_encryption_settings/chat_encryption_settings.dart';
|
||||
import 'package:tatchat/utils/beautify_string_extension.dart';
|
||||
import 'package:tatchat/utils/date_time_extension.dart';
|
||||
import 'package:tatchat/widgets/layouts/max_width_body.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
class ChatEncryptionSettingsView extends StatelessWidget {
|
||||
final ChatEncryptionSettingsController controller;
|
||||
|
||||
const ChatEncryptionSettingsView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final room = controller.room;
|
||||
return StreamBuilder<Object>(
|
||||
stream: room.client.onSync.stream.where(
|
||||
(s) => s.rooms?.join?[room.id] != null || s.deviceLists != null,
|
||||
),
|
||||
builder: (context, _) => Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.close_outlined),
|
||||
onPressed: () => context.go('/rooms/${controller.roomId!}'),
|
||||
),
|
||||
title: Text(L10n.of(context).encryption),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => launchUrlString(AppConfig.encryptionTutorial),
|
||||
child: Text(L10n.of(context).help),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.symmetric(horizontal: 16),
|
||||
title: Text(L10n.of(context).encryptThisChat),
|
||||
value: room.encrypted,
|
||||
onChanged: controller.enableEncryption,
|
||||
),
|
||||
Divider(color: theme.dividerColor, height: 1),
|
||||
if (room.isDirectChat && room.encrypted) ...[
|
||||
const SizedBox(height: 16),
|
||||
ListTile(
|
||||
title: Text(L10n.of(context).interactiveVerification),
|
||||
subtitle: Text(
|
||||
L10n.of(context).interactiveVerificationDescription,
|
||||
style: TextStyle(fontSize: 11),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
bottom: 16.0,
|
||||
left: 16,
|
||||
right: 16,
|
||||
),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.primaryContainer,
|
||||
foregroundColor: theme.colorScheme.onPrimaryContainer,
|
||||
side: BorderSide(
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
onPressed: controller.startVerification,
|
||||
icon: const Icon(Icons.verified_outlined),
|
||||
label: Text(L10n.of(context).verifyStart),
|
||||
),
|
||||
),
|
||||
),
|
||||
Divider(color: theme.dividerColor, height: 1),
|
||||
],
|
||||
if (room.encrypted) ...[
|
||||
// TODO: Display device keys
|
||||
SelectionArea(
|
||||
child: FutureBuilder(
|
||||
future: room.requestParticipants(),
|
||||
builder: (context, snapshot) {
|
||||
final users = snapshot.data;
|
||||
if (users == null) {
|
||||
return Center(
|
||||
child: CircularProgressIndicator.adaptive(),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: users.map((user) {
|
||||
final userDeviceKeys =
|
||||
room.client.userDeviceKeys[user.id];
|
||||
final masterKey = userDeviceKeys?.masterKey;
|
||||
final tofuSince = masterKey?.trustOnFirstUseSince;
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
ListTile(
|
||||
leading: CircleAvatar(
|
||||
child: Text(
|
||||
(userDeviceKeys?.deviceKeys.length ?? 0)
|
||||
.toString(),
|
||||
),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
user.calcDisplayname(),
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: .start,
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Text(
|
||||
user.id,
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
style: TextStyle(
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
masterKey == null
|
||||
? L10n.of(context).noUserKeyFound
|
||||
: masterKey.verified == true
|
||||
? L10n.of(context).verified
|
||||
: tofuSince != null
|
||||
? L10n.of(context).knownSince(
|
||||
tofuSince.localizedTime(context),
|
||||
)
|
||||
: L10n.of(context).unverified,
|
||||
style: TextStyle(
|
||||
color: masterKey == null
|
||||
? theme.colorScheme.onErrorContainer
|
||||
: masterKey.verified
|
||||
? Colors.green
|
||||
: tofuSince != null
|
||||
? theme.colorScheme.primary
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
trailing: IconButton(
|
||||
onPressed: () =>
|
||||
controller.uncollapse(user.id),
|
||||
icon: Icon(
|
||||
controller.uncollapsedUserId == user.id
|
||||
? Icons.keyboard_arrow_up_outlined
|
||||
: Icons.keyboard_arrow_down_outlined,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (controller.uncollapsedUserId == user.id &&
|
||||
userDeviceKeys != null) ...[
|
||||
...userDeviceKeys.deviceKeys.values.map((
|
||||
device,
|
||||
) {
|
||||
final signedDevice = device
|
||||
.hasValidSignatureChain(
|
||||
verifiedOnly: false,
|
||||
verifiedByTheirMasterKey: true,
|
||||
);
|
||||
return ListTile(
|
||||
title: Text(
|
||||
device.verified
|
||||
? L10n.of(context).verified
|
||||
: device.blocked
|
||||
? L10n.of(context).blocked
|
||||
: !signedDevice
|
||||
? L10n.of(context).unsignedDevice
|
||||
: L10n.of(context).signedDevice,
|
||||
style: TextStyle(
|
||||
color: device.verified
|
||||
? Colors.green
|
||||
: device.blocked
|
||||
? theme.colorScheme.error
|
||||
: !signedDevice
|
||||
? theme.colorScheme.onErrorContainer
|
||||
: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
device.curve25519Key?.beautified ??
|
||||
L10n.of(context).noCurve25519KeyFound,
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: Icon(Icons.block_outlined),
|
||||
style: IconButton.styleFrom(
|
||||
foregroundColor: device.blocked
|
||||
? theme.colorScheme.error
|
||||
: null,
|
||||
),
|
||||
tooltip: device.blocked
|
||||
? L10n.of(context).unblockDevice
|
||||
: L10n.of(context).blockDevice,
|
||||
|
||||
onPressed: () =>
|
||||
controller.toggleBlocked(device),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
Divider(color: theme.dividerColor, height: 1),
|
||||
],
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
] else
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
L10n.of(context).encryptionNotEnabled,
|
||||
style: const TextStyle(fontStyle: FontStyle.italic),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
49
lib/pages/chat_list/active_call_indicator.dart
Normal file
49
lib/pages/chat_list/active_call_indicator.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/widgets/pulsating_widget.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ActiveCallIndicator extends StatelessWidget {
|
||||
final Room room;
|
||||
const ActiveCallIndicator({required this.room, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return PulsatingWidget(
|
||||
spreadRadius: 3.0,
|
||||
color: theme.colorScheme.error,
|
||||
child: Material(
|
||||
color: theme.colorScheme.error,
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Row(
|
||||
spacing: 4.0,
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Icon(
|
||||
switch (room.activeMatrixRtcCallIntent) {
|
||||
.voice => Icons.video_call_outlined,
|
||||
_ => Icons.mic_outlined,
|
||||
},
|
||||
size: 16,
|
||||
color: theme.colorScheme.onError,
|
||||
),
|
||||
Text(
|
||||
room.getActiveMatrixRtcMembers().length.toString(),
|
||||
style: TextStyle(color: theme.colorScheme.onError),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
1098
lib/pages/chat_list/chat_list.dart
Normal file
1098
lib/pages/chat_list/chat_list.dart
Normal file
File diff suppressed because it is too large
Load Diff
338
lib/pages/chat_list/chat_list_body.dart
Normal file
338
lib/pages/chat_list/chat_list_body.dart
Normal file
@@ -0,0 +1,338 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list_item.dart';
|
||||
import 'package:tatchat/pages/chat_list/dummy_chat_list_item.dart';
|
||||
import 'package:tatchat/pages/chat_list/search_title.dart';
|
||||
import 'package:tatchat/pages/chat_list/space_view.dart';
|
||||
import 'package:tatchat/utils/stream_extension.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/public_room_dialog.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../config/themes.dart';
|
||||
import '../../widgets/adaptive_dialogs/user_dialog.dart';
|
||||
import '../../widgets/matrix.dart';
|
||||
import 'chat_list_header.dart';
|
||||
|
||||
class ChatListViewBody extends StatelessWidget {
|
||||
final ChatListController controller;
|
||||
|
||||
const ChatListViewBody(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final client = Matrix.of(context).client;
|
||||
final activeSpace = controller.activeSpaceId;
|
||||
if (activeSpace != null) {
|
||||
return SpaceView(
|
||||
key: ValueKey(activeSpace),
|
||||
spaceId: activeSpace,
|
||||
onBack: controller.clearActiveSpace,
|
||||
onChatTab: controller.onChatTap,
|
||||
activeChat: controller.activeChat,
|
||||
);
|
||||
}
|
||||
final spaces = client.rooms.where((r) => r.isSpace);
|
||||
final spaceDelegateCandidates = <String, Room>{};
|
||||
for (final space in spaces) {
|
||||
for (final spaceChild in space.spaceChildren) {
|
||||
final roomId = spaceChild.roomId;
|
||||
if (roomId == null) continue;
|
||||
spaceDelegateCandidates[roomId] = space;
|
||||
}
|
||||
}
|
||||
|
||||
final publicRooms = controller.roomSearchResult?.chunk
|
||||
.where((room) => room.roomType != 'm.space')
|
||||
.toList();
|
||||
final publicSpaces = controller.roomSearchResult?.chunk
|
||||
.where((room) => room.roomType == 'm.space')
|
||||
.toList();
|
||||
final userSearchResult = controller.userSearchResult;
|
||||
const dummyChatCount = 4;
|
||||
final filter = controller.searchController.text.toLowerCase();
|
||||
return StreamBuilder(
|
||||
key: ValueKey(client.userID.toString()),
|
||||
stream: client.onSync.stream
|
||||
.where((s) => s.hasRoomUpdate)
|
||||
.rateLimit(const Duration(seconds: 1)),
|
||||
builder: (context, _) {
|
||||
final rooms = controller.filteredRooms
|
||||
.where(
|
||||
(room) =>
|
||||
!AppSettings.hideRoomsInSpaces.value ||
|
||||
spaceDelegateCandidates[room.id] == null,
|
||||
)
|
||||
.toList();
|
||||
|
||||
return CustomScrollView(
|
||||
controller: controller.scrollController,
|
||||
slivers: [
|
||||
ChatListHeader(controller: controller),
|
||||
SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
if (controller.isSearchMode) ...[
|
||||
SearchTitle(
|
||||
title: L10n.of(context).publicRooms,
|
||||
icon: const Icon(Icons.explore_outlined),
|
||||
),
|
||||
PublicRoomsHorizontalList(publicRooms: publicRooms),
|
||||
SearchTitle(
|
||||
title: L10n.of(context).publicSpaces,
|
||||
icon: const Icon(Icons.workspaces_outlined),
|
||||
),
|
||||
PublicRoomsHorizontalList(publicRooms: publicSpaces),
|
||||
SearchTitle(
|
||||
title: L10n.of(context).users,
|
||||
icon: const Icon(Icons.group_outlined),
|
||||
),
|
||||
AnimatedContainer(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
decoration: const BoxDecoration(),
|
||||
height:
|
||||
userSearchResult == null ||
|
||||
userSearchResult.results.isEmpty
|
||||
? 0
|
||||
: 106,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: userSearchResult == null
|
||||
? null
|
||||
: ListView.builder(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: userSearchResult.results.length,
|
||||
itemBuilder: (context, i) => _SearchItem(
|
||||
title:
|
||||
userSearchResult.results[i].displayName ??
|
||||
userSearchResult
|
||||
.results[i]
|
||||
.userId
|
||||
.localpart ??
|
||||
L10n.of(context).unknownDevice,
|
||||
avatar: userSearchResult.results[i].avatarUrl,
|
||||
onPressed: () => UserDialog.show(
|
||||
context: context,
|
||||
profile: userSearchResult.results[i],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (client.rooms.isNotEmpty && !controller.isSearchMode)
|
||||
Container(
|
||||
height: 36 + 8 + 8,
|
||||
padding: EdgeInsets.symmetric(vertical: 8),
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
||||
shrinkWrap: true,
|
||||
scrollDirection: Axis.horizontal,
|
||||
children: [
|
||||
...ActiveFilter.values
|
||||
.where((filter) => filter != ActiveFilter.tag)
|
||||
.map(
|
||||
(filter) => Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 4.0,
|
||||
),
|
||||
child: Center(
|
||||
child: FilterChip(
|
||||
selected: filter == controller.activeFilter,
|
||||
onSelected: (_) => controller
|
||||
.setActiveFilter(filter, null),
|
||||
label: Text(
|
||||
filter.toLocalizedString(context),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
...controller.roomTags.entries.map(
|
||||
(entry) => Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 4.0,
|
||||
),
|
||||
child: Center(
|
||||
child: FilterChip(
|
||||
selected: entry.key == controller.activeTag,
|
||||
onSelected: (_) => controller.setActiveFilter(
|
||||
ActiveFilter.tag,
|
||||
entry.key,
|
||||
),
|
||||
label: Text(entry.key.replaceFirst('u.', '')),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (controller.isSearchMode)
|
||||
SearchTitle(
|
||||
title: L10n.of(context).chats,
|
||||
icon: const Icon(Icons.forum_outlined),
|
||||
),
|
||||
if (client.prevBatch != null &&
|
||||
rooms.isEmpty &&
|
||||
!controller.isSearchMode) ...[
|
||||
Column(
|
||||
mainAxisAlignment: .center,
|
||||
children: [
|
||||
Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
const Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
DummyChatListItem(opacity: 0.5, animate: false),
|
||||
DummyChatListItem(opacity: 0.3, animate: false),
|
||||
],
|
||||
),
|
||||
Icon(
|
||||
CupertinoIcons.chat_bubble_text_fill,
|
||||
size: 128,
|
||||
color: theme.colorScheme.secondary,
|
||||
),
|
||||
],
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
client.rooms.isEmpty
|
||||
? L10n.of(context).noChatsFoundHere
|
||||
: L10n.of(context).noMoreChatsFound,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
color: theme.colorScheme.secondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
]),
|
||||
),
|
||||
if (client.prevBatch == null)
|
||||
SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(context, i) => DummyChatListItem(
|
||||
opacity: (dummyChatCount - i) / dummyChatCount,
|
||||
animate: true,
|
||||
),
|
||||
childCount: dummyChatCount,
|
||||
),
|
||||
),
|
||||
if (client.prevBatch != null)
|
||||
SliverSafeArea(
|
||||
top: false,
|
||||
sliver: SliverList.builder(
|
||||
itemCount: rooms.length,
|
||||
itemBuilder: (BuildContext context, int i) {
|
||||
final room = rooms[i];
|
||||
final space = spaceDelegateCandidates[room.id];
|
||||
return ChatListItem(
|
||||
room,
|
||||
space: space,
|
||||
key: Key('chat_list_item_${room.id}'),
|
||||
filter: filter,
|
||||
onTap: () => controller.onChatTap(room),
|
||||
onLongPress: (context) =>
|
||||
controller.chatContextAction(room, context, space),
|
||||
activeChat: controller.activeChat == room.id,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PublicRoomsHorizontalList extends StatelessWidget {
|
||||
const PublicRoomsHorizontalList({super.key, required this.publicRooms});
|
||||
|
||||
final List<PublishedRoomsChunk>? publicRooms;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final publicRooms = this.publicRooms;
|
||||
return AnimatedContainer(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
decoration: const BoxDecoration(),
|
||||
height: publicRooms == null || publicRooms.isEmpty ? 0 : 106,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: publicRooms == null
|
||||
? null
|
||||
: ListView.builder(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: publicRooms.length,
|
||||
itemBuilder: (context, i) => _SearchItem(
|
||||
title:
|
||||
publicRooms[i].name ??
|
||||
publicRooms[i].canonicalAlias?.localpart ??
|
||||
L10n.of(context).group,
|
||||
avatar: publicRooms[i].avatarUrl,
|
||||
onPressed: () => showAdaptiveDialog(
|
||||
context: context,
|
||||
barrierDismissible: true,
|
||||
builder: (c) => PublicRoomDialog(
|
||||
roomAlias:
|
||||
publicRooms[i].canonicalAlias ?? publicRooms[i].roomId,
|
||||
chunk: publicRooms[i],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SearchItem extends StatelessWidget {
|
||||
final String title;
|
||||
final Uri? avatar;
|
||||
final void Function() onPressed;
|
||||
|
||||
const _SearchItem({
|
||||
required this.title,
|
||||
this.avatar,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => InkWell(
|
||||
onTap: onPressed,
|
||||
child: SizedBox(
|
||||
width: 84,
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
Avatar(mxContent: avatar, name: title),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
title,
|
||||
maxLines: 2,
|
||||
textAlign: TextAlign.center,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
152
lib/pages/chat_list/chat_list_header.dart
Normal file
152
lib/pages/chat_list/chat_list_header.dart
Normal file
@@ -0,0 +1,152 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list.dart';
|
||||
import 'package:tatchat/pages/chat_list/client_chooser_button.dart';
|
||||
import 'package:tatchat/utils/sync_status_localization.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../widgets/matrix.dart';
|
||||
|
||||
class ChatListHeader extends StatelessWidget implements PreferredSizeWidget {
|
||||
final ChatListController controller;
|
||||
final bool globalSearch;
|
||||
|
||||
const ChatListHeader({
|
||||
super.key,
|
||||
required this.controller,
|
||||
this.globalSearch = true,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final client = Matrix.of(context).client;
|
||||
final isColumnMode = FluffyThemes.isColumnMode(context);
|
||||
|
||||
return SliverAppBar(
|
||||
floating: true,
|
||||
toolbarHeight: 72,
|
||||
pinned: isColumnMode,
|
||||
scrolledUnderElevation: 0,
|
||||
shape: isColumnMode
|
||||
? Border(bottom: BorderSide(color: theme.dividerColor, width: 1))
|
||||
: null,
|
||||
backgroundColor: isColumnMode
|
||||
? theme.colorScheme.surface.withAlpha(240)
|
||||
: Colors.transparent,
|
||||
automaticallyImplyLeading: false,
|
||||
title: StreamBuilder(
|
||||
stream: client.onSyncStatus.stream,
|
||||
builder: (context, snapshot) {
|
||||
final status =
|
||||
client.onSyncStatus.value ??
|
||||
const SyncStatusUpdate(SyncStatus.waitingForResponse);
|
||||
final hide =
|
||||
client.onSync.value != null &&
|
||||
status.status != SyncStatus.error &&
|
||||
client.prevBatch != null;
|
||||
return TextField(
|
||||
controller: controller.searchController,
|
||||
focusNode: controller.searchFocusNode,
|
||||
textInputAction: TextInputAction.search,
|
||||
onChanged: (text) =>
|
||||
controller.onSearchEnter(text, globalSearch: globalSearch),
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.secondaryContainer,
|
||||
border: OutlineInputBorder(
|
||||
borderSide: BorderSide.none,
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
),
|
||||
hintText: hide
|
||||
? L10n.of(context).searchChatsRooms
|
||||
: status.calcLocalizedString(context),
|
||||
hintStyle: TextStyle(
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
|
||||
prefixIcon: hide
|
||||
? controller.isSearchMode
|
||||
? IconButton(
|
||||
tooltip: L10n.of(context).cancel,
|
||||
icon: const Icon(Icons.close_outlined),
|
||||
onPressed: controller.cancelSearch,
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
)
|
||||
: isColumnMode ||
|
||||
(controller.spaces.isEmpty &&
|
||||
!AppSettings.displayNavigationRail.value)
|
||||
? IconButton(
|
||||
tooltip: L10n.of(context).search,
|
||||
onPressed: controller.startSearch,
|
||||
icon: Icon(
|
||||
Icons.search_outlined,
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
),
|
||||
)
|
||||
: IconButton(
|
||||
tooltip: L10n.of(context).displayNavigationRail,
|
||||
onPressed: controller.openNavrail,
|
||||
icon: Icon(
|
||||
Icons.menu,
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
),
|
||||
)
|
||||
: SizedBox(
|
||||
width: 8,
|
||||
height: 8,
|
||||
child: Center(
|
||||
child: CircularProgressIndicator.adaptive(
|
||||
strokeWidth: 2,
|
||||
value: status.progress,
|
||||
),
|
||||
),
|
||||
),
|
||||
suffixIcon: controller.isSearchMode && globalSearch
|
||||
? controller.isSearching
|
||||
? const Padding(
|
||||
padding: EdgeInsets.symmetric(
|
||||
vertical: 10.0,
|
||||
horizontal: 12,
|
||||
),
|
||||
child: SizedBox.square(
|
||||
dimension: 24,
|
||||
child: CircularProgressIndicator.adaptive(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
),
|
||||
)
|
||||
: TextButton.icon(
|
||||
onPressed: controller.setServer,
|
||||
style: TextButton.styleFrom(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
),
|
||||
textStyle: const TextStyle(fontSize: 12),
|
||||
),
|
||||
icon: const Icon(Icons.edit_outlined, size: 16),
|
||||
label: Text(
|
||||
controller.searchServer ??
|
||||
Matrix.of(context).client.homeserver!.host,
|
||||
maxLines: 2,
|
||||
),
|
||||
)
|
||||
: SizedBox(width: 0, child: ClientChooserButton(controller)),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Size get preferredSize => const Size.fromHeight(56);
|
||||
}
|
||||
412
lib/pages/chat_list/chat_list_item.dart
Normal file
412
lib/pages/chat_list/chat_list_item.dart
Normal file
@@ -0,0 +1,412 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/active_call_indicator.dart';
|
||||
import 'package:tatchat/pages/chat_list/unread_bubble.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/utils/room_status_extension.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/hover_builder.dart';
|
||||
import 'package:tatchat/widgets/typing_animation.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../config/themes.dart';
|
||||
import '../../utils/date_time_extension.dart';
|
||||
import '../../widgets/avatar.dart';
|
||||
|
||||
class ChatListItem extends StatelessWidget {
|
||||
final Room room;
|
||||
final Room? space;
|
||||
final bool activeChat;
|
||||
final void Function(BuildContext context)? onLongPress;
|
||||
final void Function()? onForget;
|
||||
final void Function() onTap;
|
||||
final String? filter;
|
||||
|
||||
const ChatListItem(
|
||||
this.room, {
|
||||
this.activeChat = false,
|
||||
required this.onTap,
|
||||
this.onLongPress,
|
||||
this.onForget,
|
||||
this.filter,
|
||||
this.space,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final isMuted = room.pushRuleState != PushRuleState.notify;
|
||||
final typingText = room.getLocalizedTypingText(context);
|
||||
final lastEvent = room.lastEvent;
|
||||
final ownMessage = lastEvent?.senderId == room.client.userID;
|
||||
final directChatMatrixId = room.directChatMatrixID;
|
||||
final isDirectChat = directChatMatrixId != null;
|
||||
final hasNotifications = room.notificationCount > 0;
|
||||
final backgroundColor = activeChat
|
||||
? theme.colorScheme.secondaryContainer
|
||||
: null;
|
||||
final displayname = room.getLocalizedDisplayname(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
);
|
||||
final filter = this.filter;
|
||||
if (filter != null && !displayname.toLowerCase().contains(filter)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final needLastEventSender =
|
||||
lastEvent != null &&
|
||||
room.getState(EventTypes.RoomMember, lastEvent.senderId) == null;
|
||||
final space = this.space;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
color: backgroundColor,
|
||||
child: FutureBuilder(
|
||||
future: room.name.isEmpty ? room.loadHeroUsers() : null,
|
||||
builder: (context, _) => HoverBuilder(
|
||||
builder: (context, listTileHovered) => ListTile(
|
||||
minVerticalPadding: 16,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onLongPress: () => onLongPress?.call(context),
|
||||
leading: HoverBuilder(
|
||||
builder: (context, hovered) => AnimatedScale(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
scale: hovered ? 1.1 : 1.0,
|
||||
child: SizedBox(
|
||||
width: Avatar.defaultSize,
|
||||
height: Avatar.defaultSize,
|
||||
child: Stack(
|
||||
children: [
|
||||
if (space != null)
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
child: Avatar(
|
||||
shapeBorder: RoundedSuperellipseBorder(
|
||||
side: BorderSide(
|
||||
width: 2,
|
||||
color:
|
||||
backgroundColor ??
|
||||
theme.colorScheme.surface,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius * 0.75,
|
||||
),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius * 0.75,
|
||||
),
|
||||
mxContent: space.avatar,
|
||||
size: Avatar.defaultSize * 0.75,
|
||||
name: space.getLocalizedDisplayname(),
|
||||
onTap: () => onLongPress?.call(context),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
child: Avatar(
|
||||
shapeBorder: space == null
|
||||
? room.isSpace
|
||||
? RoundedSuperellipseBorder(
|
||||
side: BorderSide(
|
||||
width: 1,
|
||||
color: theme.dividerColor,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius,
|
||||
),
|
||||
)
|
||||
: null
|
||||
: RoundedRectangleBorder(
|
||||
side: BorderSide(
|
||||
width: 2,
|
||||
color:
|
||||
backgroundColor ??
|
||||
theme.colorScheme.surface,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
Avatar.defaultSize,
|
||||
),
|
||||
),
|
||||
borderRadius: room.isSpace
|
||||
? BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius,
|
||||
)
|
||||
: null,
|
||||
mxContent: room.avatar,
|
||||
size: space != null
|
||||
? Avatar.defaultSize * 0.75
|
||||
: Avatar.defaultSize,
|
||||
name: displayname,
|
||||
presenceUserId: directChatMatrixId,
|
||||
presenceBackgroundColor: backgroundColor,
|
||||
onTap: () => onLongPress?.call(context),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 0,
|
||||
right: 0,
|
||||
child: GestureDetector(
|
||||
onTap: () => onLongPress?.call(context),
|
||||
child: AnimatedScale(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
scale: listTileHovered ? 1.0 : 0.0,
|
||||
child: Material(
|
||||
color: backgroundColor,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: const Icon(
|
||||
Icons.arrow_drop_down_circle_outlined,
|
||||
size: 18,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
title: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(
|
||||
displayname,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
softWrap: false,
|
||||
),
|
||||
),
|
||||
if (isMuted)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 4.0),
|
||||
child: Icon(Icons.notifications_off_outlined, size: 16),
|
||||
),
|
||||
if (room.isLowPriority)
|
||||
Padding(
|
||||
padding: EdgeInsets.only(
|
||||
right: hasNotifications ? 4.0 : 0.0,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.low_priority,
|
||||
size: 16,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
if (room.isFavourite)
|
||||
Padding(
|
||||
padding: EdgeInsets.only(
|
||||
right: hasNotifications ? 4.0 : 0.0,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.push_pin,
|
||||
size: 16,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
),
|
||||
if (!room.isSpace && room.membership != Membership.invite)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 4.0),
|
||||
child: Text(
|
||||
room.latestEventReceivedTime.localizedTimeShort(
|
||||
context,
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: room.hasNewMessages
|
||||
? FontWeight.bold
|
||||
: null,
|
||||
color: room.highlightCount >= 1
|
||||
? theme.colorScheme.error
|
||||
: room.hasNewMessages
|
||||
? theme.colorScheme.primary
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
subtitle: Row(
|
||||
children: [
|
||||
if (room.hasActiveMatrixRtcCall)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 4.0),
|
||||
child: ActiveCallIndicator(room: room),
|
||||
),
|
||||
if (typingText.isEmpty &&
|
||||
ownMessage &&
|
||||
room.lastEvent?.status.isSending == true) ...[
|
||||
const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator.adaptive(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
AnimatedSize(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: typingText.isNotEmpty
|
||||
? Padding(
|
||||
padding: const EdgeInsets.only(right: 4.0),
|
||||
child: TypingAnimation(size: 4.0),
|
||||
)
|
||||
: room.lastEvent?.relationshipType ==
|
||||
RelationshipTypes.thread
|
||||
? Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.outline,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius,
|
||||
),
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8.0,
|
||||
),
|
||||
margin: const EdgeInsets.only(right: 4.0),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.message_outlined,
|
||||
size: 12,
|
||||
color: theme.colorScheme.outline,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
L10n.of(context).thread,
|
||||
style: TextStyle(fontSize: 11),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
Expanded(
|
||||
child: room.isSpace && room.membership == Membership.join
|
||||
? Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).countChats(room.spaceChildren.length),
|
||||
)
|
||||
: typingText.isNotEmpty
|
||||
? Text(
|
||||
typingText,
|
||||
style: TextStyle(color: theme.colorScheme.primary),
|
||||
maxLines: 1,
|
||||
softWrap: false,
|
||||
)
|
||||
: FutureBuilder(
|
||||
key: ValueKey(
|
||||
'${lastEvent?.eventId}_${lastEvent?.type}_${lastEvent?.redacted}',
|
||||
),
|
||||
future: needLastEventSender
|
||||
? lastEvent.calcLocalizedBody(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
hideReply: true,
|
||||
hideEdit: true,
|
||||
plaintextBody: true,
|
||||
removeMarkdown: true,
|
||||
withSenderNamePrefix:
|
||||
(!isDirectChat ||
|
||||
directChatMatrixId !=
|
||||
room.lastEvent?.senderId),
|
||||
)
|
||||
: null,
|
||||
initialData: lastEvent?.calcLocalizedBodyFallback(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
hideReply: true,
|
||||
hideEdit: true,
|
||||
plaintextBody: true,
|
||||
removeMarkdown: true,
|
||||
withSenderNamePrefix:
|
||||
(!isDirectChat ||
|
||||
directChatMatrixId !=
|
||||
room.lastEvent?.senderId),
|
||||
),
|
||||
builder: (context, snapshot) => Text(
|
||||
room.membership == Membership.invite
|
||||
? room
|
||||
.getState(
|
||||
EventTypes.RoomMember,
|
||||
room.client.userID!,
|
||||
)
|
||||
?.content
|
||||
.tryGet<String>('reason') ??
|
||||
(isDirectChat
|
||||
? L10n.of(context).newChatRequest
|
||||
: L10n.of(context).inviteGroupChat)
|
||||
: snapshot.data?.trim().replaceAll(
|
||||
'\n',
|
||||
' ',
|
||||
) ??
|
||||
L10n.of(context).noMessagesYet,
|
||||
softWrap: false,
|
||||
maxLines: room.notificationCount >= 1 ? 2 : 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
decoration: room.lastEvent?.redacted == true
|
||||
? TextDecoration.lineThrough
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
UnreadBubble(room: room),
|
||||
],
|
||||
),
|
||||
onTap: onTap,
|
||||
trailing: onForget == null
|
||||
? room.membership == Membership.invite
|
||||
? IconButton(
|
||||
tooltip: L10n.of(context).declineInvitation,
|
||||
icon: const Icon(Icons.delete_forever_outlined),
|
||||
color: theme.colorScheme.error,
|
||||
onPressed: () async {
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).declineInvitation,
|
||||
message: L10n.of(context).areYouSure,
|
||||
okLabel: L10n.of(context).yes,
|
||||
isDestructive: true,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!context.mounted) return;
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: room.leave,
|
||||
);
|
||||
},
|
||||
)
|
||||
: null
|
||||
: IconButton(
|
||||
icon: const Icon(Icons.delete_outlined),
|
||||
onPressed: onForget,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
146
lib/pages/chat_list/chat_list_view.dart
Normal file
146
lib/pages/chat_list/chat_list_view.dart
Normal file
@@ -0,0 +1,146 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list.dart';
|
||||
import 'package:tatchat/pages/chat_list/navigation_rail.dart';
|
||||
import 'package:tatchat/pages/chat_list/start_chat_fab.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/channels_tab.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/chat_tab_bar.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/home_tab.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/murals_tab.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/spaces_tab.dart';
|
||||
|
||||
import 'chat_list_body.dart';
|
||||
|
||||
class ChatListView extends StatelessWidget {
|
||||
final ChatListController controller;
|
||||
|
||||
const ChatListView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final oneColumnSpacesMode =
|
||||
!FluffyThemes.isColumnMode(context) &&
|
||||
AppSettings.displayNavigationRail.value;
|
||||
final isColumnMode = FluffyThemes.isColumnMode(context);
|
||||
final homeTab = controller.homeTab;
|
||||
final showSpacesMode = homeTab == HomeTab.chats;
|
||||
final showNavigationRail =
|
||||
showSpacesMode &&
|
||||
(isColumnMode || AppSettings.displayNavigationRail.value);
|
||||
return PopScope(
|
||||
canPop: !controller.isSearchMode && controller.activeSpaceId == null,
|
||||
onPopInvokedWithResult: (pop, _) {
|
||||
if (pop) return;
|
||||
if (controller.activeSpaceId != null) {
|
||||
controller.clearActiveSpace();
|
||||
return;
|
||||
}
|
||||
if (controller.isSearchMode) {
|
||||
controller.cancelSearch();
|
||||
return;
|
||||
}
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (isColumnMode)
|
||||
ChatTopTabBar(
|
||||
currentTab: homeTab,
|
||||
onTabSelected: controller.setHomeTab,
|
||||
),
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: AnimatedSize(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: showNavigationRail
|
||||
? SpacesNavigationRail(
|
||||
activeSpaceId: controller.activeSpaceId,
|
||||
onGoToChats: controller.clearActiveSpace,
|
||||
onGoToSpaceId: controller.setActiveSpace,
|
||||
)
|
||||
: SizedBox(
|
||||
width: 0,
|
||||
height: MediaQuery.sizeOf(context).height,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (showNavigationRail && isColumnMode)
|
||||
Container(width: 1, color: Theme.of(context).dividerColor),
|
||||
|
||||
Expanded(
|
||||
child: Scaffold(
|
||||
backgroundColor: showSpacesMode && oneColumnSpacesMode
|
||||
? Theme.of(context).colorScheme.surfaceContainer
|
||||
: null,
|
||||
body: SafeArea(
|
||||
top: showSpacesMode && oneColumnSpacesMode,
|
||||
bottom: false,
|
||||
left: false,
|
||||
right: false,
|
||||
child: IndexedStack(
|
||||
index: homeTab.index,
|
||||
children: [
|
||||
Material(
|
||||
clipBehavior: showSpacesMode && oneColumnSpacesMode
|
||||
? Clip.hardEdge
|
||||
: Clip.none,
|
||||
borderRadius:
|
||||
showSpacesMode && oneColumnSpacesMode
|
||||
? BorderRadius.only(
|
||||
topLeft: Radius.circular(
|
||||
AppConfig.borderRadius,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
color: showSpacesMode && oneColumnSpacesMode
|
||||
? Theme.of(context).colorScheme.surface
|
||||
: null,
|
||||
child: ChatListViewBody(controller),
|
||||
),
|
||||
ChannelsTab(controller),
|
||||
SpacesTab(controller),
|
||||
MuralsTab(),
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton:
|
||||
showSpacesMode &&
|
||||
!controller.isSearchMode &&
|
||||
controller.activeSpaceId == null &&
|
||||
!isColumnMode
|
||||
? ValueListenableBuilder(
|
||||
valueListenable: controller.scrolledToTop,
|
||||
builder: (context, scrolledToTop, _) => StartChatFab(
|
||||
extended:
|
||||
scrolledToTop &&
|
||||
!AppSettings.displayNavigationRail.value,
|
||||
),
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
bottomNavigationBar: isColumnMode
|
||||
? null
|
||||
: ChatBottomTabBar(
|
||||
currentTab: homeTab,
|
||||
onTabSelected: controller.setHomeTab,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
241
lib/pages/chat_list/client_chooser_button.dart
Normal file
241
lib/pages/chat_list/client_chooser_button.dart
Normal file
@@ -0,0 +1,241 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:async/async.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart' hide Result;
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
import 'package:tatchat/utils/tatu_share.dart';
|
||||
import 'chat_list.dart';
|
||||
|
||||
class ClientChooserButton extends StatelessWidget {
|
||||
final ChatListController controller;
|
||||
|
||||
const ClientChooserButton(this.controller, {super.key});
|
||||
|
||||
List<PopupMenuEntry<Object>> _bundleMenuItems(BuildContext context) {
|
||||
final matrix = Matrix.of(context);
|
||||
final bundles = matrix.accountBundles.keys.toList()
|
||||
..sort(
|
||||
(a, b) => a!.isValidMatrixIdStrict() == b!.isValidMatrixIdStrict()
|
||||
? 0
|
||||
: a.isValidMatrixIdStrict() && !b.isValidMatrixIdStrict()
|
||||
? -1
|
||||
: 1,
|
||||
);
|
||||
return <PopupMenuEntry<Object>>[
|
||||
PopupMenuItem(
|
||||
value: SettingsAction.newGroup,
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.group_add_outlined),
|
||||
const SizedBox(width: 18),
|
||||
Text(L10n.of(context).createGroup),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SettingsAction.setStatus,
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.edit_outlined),
|
||||
const SizedBox(width: 18),
|
||||
Text(L10n.of(context).setStatus),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SettingsAction.invite,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.adaptive.share_outlined),
|
||||
const SizedBox(width: 18),
|
||||
Text(L10n.of(context).inviteContact),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SettingsAction.archive,
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.archive_outlined),
|
||||
const SizedBox(width: 18),
|
||||
Text(L10n.of(context).archive),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SettingsAction.settings,
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.settings_outlined),
|
||||
const SizedBox(width: 18),
|
||||
Text(L10n.of(context).settings),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SettingsAction.support,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.favorite, color: Colors.red),
|
||||
const SizedBox(width: 18),
|
||||
Text(L10n.of(context).supportFluffyChat),
|
||||
],
|
||||
),
|
||||
),
|
||||
const PopupMenuDivider(),
|
||||
for (final bundle in bundles) ...[
|
||||
if (matrix.accountBundles[bundle]!.length != 1 ||
|
||||
matrix.accountBundles[bundle]!.single!.userID != bundle)
|
||||
PopupMenuItem(
|
||||
value: null,
|
||||
child: Column(
|
||||
crossAxisAlignment: .start,
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Text(
|
||||
bundle!,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).textTheme.titleMedium!.color,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
],
|
||||
),
|
||||
),
|
||||
...matrix.accountBundles[bundle]!
|
||||
.whereType<Client>()
|
||||
.where((client) => client.isLogged())
|
||||
.map(
|
||||
(client) => PopupMenuItem(
|
||||
value: client,
|
||||
child: FutureBuilder<Profile?>(
|
||||
future: client.fetchOwnProfile(),
|
||||
builder: (context, snapshot) {
|
||||
final displayname =
|
||||
snapshot.data?.displayName ?? client.userID!.localpart!;
|
||||
return Row(
|
||||
key: ValueKey('switch_account_$displayname'),
|
||||
children: [
|
||||
Avatar(
|
||||
mxContent: snapshot.data?.avatarUrl,
|
||||
name: displayname,
|
||||
size: 32,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
displayname,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit_outlined),
|
||||
onPressed: () => controller.editBundlesForAccount(
|
||||
client.userID,
|
||||
bundle,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
PopupMenuItem(
|
||||
value: SettingsAction.addAccount,
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.person_add_outlined),
|
||||
const SizedBox(width: 18),
|
||||
Text(L10n.of(context).addAccount),
|
||||
],
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final matrix = Matrix.of(context);
|
||||
final client = Result(() => matrix.client).asValue?.value;
|
||||
|
||||
var clientCount = 0;
|
||||
matrix.accountBundles.forEach((key, value) => clientCount += value.length);
|
||||
return FutureBuilder<Profile>(
|
||||
future: client?.isLogged() == true ? client?.fetchOwnProfile() : null,
|
||||
builder: (context, snapshot) => Material(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
color: Colors.transparent,
|
||||
child: PopupMenuButton<Object>(
|
||||
key: Key('accounts_and_settings_buttons'),
|
||||
tooltip: L10n.of(context).accountsAndSettings,
|
||||
onSelected: (o) => _clientSelected(o, context),
|
||||
itemBuilder: _bundleMenuItems,
|
||||
icon: Avatar(
|
||||
mxContent: snapshot.data?.avatarUrl,
|
||||
name: snapshot.data?.displayName ?? client?.userID?.localpart,
|
||||
size: 32,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _clientSelected(Object object, BuildContext context) async {
|
||||
if (object is Client) {
|
||||
controller.setActiveClient(object);
|
||||
} else if (object is String) {
|
||||
controller.setActiveBundle(object);
|
||||
} else if (object is SettingsAction) {
|
||||
switch (object) {
|
||||
case SettingsAction.addAccount:
|
||||
if (!context.mounted) return;
|
||||
context.go('/rooms/settings/addaccount');
|
||||
break;
|
||||
case SettingsAction.newGroup:
|
||||
context.go('/rooms/newgroup');
|
||||
break;
|
||||
case SettingsAction.invite:
|
||||
TatuShare.shareInviteLink(context);
|
||||
break;
|
||||
case SettingsAction.support:
|
||||
launchUrlString(
|
||||
'https://ko-fi.com/post/How-can-I-support-FluffyChat-J2G325WE6I',
|
||||
);
|
||||
break;
|
||||
case SettingsAction.settings:
|
||||
context.go('/rooms/settings');
|
||||
break;
|
||||
case SettingsAction.archive:
|
||||
context.go('/rooms/archive');
|
||||
break;
|
||||
case SettingsAction.setStatus:
|
||||
controller.setStatus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum SettingsAction {
|
||||
addAccount,
|
||||
newGroup,
|
||||
setStatus,
|
||||
invite,
|
||||
support,
|
||||
settings,
|
||||
archive,
|
||||
}
|
||||
77
lib/pages/chat_list/dummy_chat_list_item.dart
Normal file
77
lib/pages/chat_list/dummy_chat_list_item.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class DummyChatListItem extends StatelessWidget {
|
||||
final double opacity;
|
||||
final bool animate;
|
||||
|
||||
const DummyChatListItem({
|
||||
required this.opacity,
|
||||
required this.animate,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final titleColor = theme.textTheme.bodyLarge!.color!.withAlpha(100);
|
||||
final subtitleColor = theme.textTheme.bodyLarge!.color!.withAlpha(50);
|
||||
return Opacity(
|
||||
opacity: opacity,
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: titleColor,
|
||||
child: animate
|
||||
? CircularProgressIndicator(
|
||||
strokeWidth: 1,
|
||||
color: theme.textTheme.bodyLarge!.color,
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Container(
|
||||
height: 14,
|
||||
decoration: BoxDecoration(
|
||||
color: titleColor,
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 36),
|
||||
Container(
|
||||
height: 14,
|
||||
width: 14,
|
||||
decoration: BoxDecoration(
|
||||
color: subtitleColor,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Container(
|
||||
height: 14,
|
||||
width: 14,
|
||||
decoration: BoxDecoration(
|
||||
color: subtitleColor,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
subtitle: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: subtitleColor,
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
height: 12,
|
||||
margin: const EdgeInsets.only(right: 22),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
103
lib/pages/chat_list/navi_rail_item.dart
Normal file
103
lib/pages/chat_list/navi_rail_item.dart
Normal file
@@ -0,0 +1,103 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:badges/badges.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/widgets/hover_builder.dart';
|
||||
import 'package:tatchat/widgets/unread_rooms_badge.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../config/themes.dart';
|
||||
|
||||
class NaviRailItem extends StatelessWidget {
|
||||
final String toolTip;
|
||||
final bool isSelected;
|
||||
final void Function() onTap;
|
||||
final Widget icon;
|
||||
final Widget? selectedIcon;
|
||||
final bool Function(Room)? unreadBadgeFilter;
|
||||
|
||||
const NaviRailItem({
|
||||
required this.toolTip,
|
||||
required this.isSelected,
|
||||
required this.onTap,
|
||||
required this.icon,
|
||||
this.selectedIcon,
|
||||
this.unreadBadgeFilter,
|
||||
super.key,
|
||||
});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final borderRadius = BorderRadius.circular(AppConfig.borderRadius);
|
||||
final icon = isSelected ? selectedIcon ?? this.icon : this.icon;
|
||||
final unreadBadgeFilter = this.unreadBadgeFilter;
|
||||
return HoverBuilder(
|
||||
builder: (context, hovered) {
|
||||
return SizedBox(
|
||||
height: 64,
|
||||
width: FluffyThemes.navRailWidth,
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned(
|
||||
top: 8,
|
||||
bottom: 8,
|
||||
left: 0,
|
||||
child: AnimatedContainer(
|
||||
width: isSelected
|
||||
? FluffyThemes.isColumnMode(context)
|
||||
? 8
|
||||
: 4
|
||||
: 0,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary,
|
||||
borderRadius: const BorderRadius.only(
|
||||
topRight: Radius.circular(90),
|
||||
bottomRight: Radius.circular(90),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: AnimatedScale(
|
||||
scale: hovered ? 1.1 : 1.0,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: Material(
|
||||
borderRadius: borderRadius,
|
||||
color: isSelected
|
||||
? theme.colorScheme.secondaryContainer
|
||||
: theme.colorScheme.surfaceContainerHighest,
|
||||
child: Tooltip(
|
||||
message: toolTip,
|
||||
child: InkWell(
|
||||
borderRadius: borderRadius,
|
||||
onTap: onTap,
|
||||
child: unreadBadgeFilter == null
|
||||
? icon
|
||||
: UnreadRoomsBadge(
|
||||
filter: unreadBadgeFilter,
|
||||
badgePosition: BadgePosition.topEnd(
|
||||
top: -12,
|
||||
end: -8,
|
||||
),
|
||||
child: icon,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
137
lib/pages/chat_list/navigation_rail.dart
Normal file
137
lib/pages/chat_list/navigation_rail.dart
Normal file
@@ -0,0 +1,137 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/navi_rail_item.dart';
|
||||
import 'package:tatchat/pages/chat_list/start_chat_fab.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/utils/stream_extension.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class SpacesNavigationRail extends StatelessWidget {
|
||||
final String? activeSpaceId;
|
||||
final void Function() onGoToChats;
|
||||
final void Function(String) onGoToSpaceId;
|
||||
|
||||
const SpacesNavigationRail({
|
||||
required this.activeSpaceId,
|
||||
required this.onGoToChats,
|
||||
required this.onGoToSpaceId,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final client = Matrix.of(context).client;
|
||||
final coloredMode = !FluffyThemes.isColumnMode(context);
|
||||
final theme = Theme.of(context);
|
||||
return Material(
|
||||
color: coloredMode ? theme.colorScheme.surfaceContainer : null,
|
||||
child: SafeArea(
|
||||
child: StreamBuilder(
|
||||
key: ValueKey(client.userID.toString()),
|
||||
stream: client.onSync.stream
|
||||
.where((s) => s.hasRoomUpdate)
|
||||
.rateLimit(const Duration(seconds: 1)),
|
||||
builder: (context, _) {
|
||||
final allSpaces = client.rooms
|
||||
.where((room) => room.isSpace)
|
||||
.toList();
|
||||
|
||||
return SizedBox(
|
||||
width: FluffyThemes.isColumnMode(context)
|
||||
? FluffyThemes.navRailWidth
|
||||
: FluffyThemes.navRailWidth - 8,
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
padding: EdgeInsets.symmetric(vertical: 4),
|
||||
scrollDirection: Axis.vertical,
|
||||
itemCount: allSpaces.length + 2,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == 0) {
|
||||
return NaviRailItem(
|
||||
isSelected: activeSpaceId == null,
|
||||
onTap: onGoToChats,
|
||||
icon: const Padding(
|
||||
padding: EdgeInsets.all(12.0),
|
||||
child: Icon(Icons.forum_outlined),
|
||||
),
|
||||
selectedIcon: const Padding(
|
||||
padding: EdgeInsets.all(12.0),
|
||||
child: Icon(Icons.forum),
|
||||
),
|
||||
toolTip: L10n.of(context).chats,
|
||||
unreadBadgeFilter: (room) => true,
|
||||
);
|
||||
}
|
||||
i--;
|
||||
if (i == allSpaces.length) {
|
||||
return NaviRailItem(
|
||||
isSelected: false,
|
||||
onTap: () => context.go('/rooms/newspace'),
|
||||
icon: const Padding(
|
||||
padding: EdgeInsets.all(12.0),
|
||||
child: Icon(Icons.add),
|
||||
),
|
||||
toolTip: L10n.of(context).createNewSpace,
|
||||
);
|
||||
}
|
||||
final space = allSpaces[i];
|
||||
final displayname = allSpaces[i]
|
||||
.getLocalizedDisplayname(
|
||||
MatrixLocals(L10n.of(context)),
|
||||
);
|
||||
final spaceChildrenIds = space.spaceChildren
|
||||
.map((c) => c.roomId)
|
||||
.toSet();
|
||||
return NaviRailItem(
|
||||
toolTip: displayname,
|
||||
isSelected: activeSpaceId == space.id,
|
||||
onTap: () => onGoToSpaceId(allSpaces[i].id),
|
||||
unreadBadgeFilter: (room) =>
|
||||
spaceChildrenIds.contains(room.id),
|
||||
icon: Avatar(
|
||||
mxContent: allSpaces[i].avatar,
|
||||
name: displayname,
|
||||
//size: 36,
|
||||
shapeBorder: RoundedSuperellipseBorder(
|
||||
side: BorderSide(
|
||||
width: 1,
|
||||
color: Theme.of(context).dividerColor,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius,
|
||||
),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
if (FluffyThemes.isColumnMode(context))
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: StartChatFab(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
71
lib/pages/chat_list/search_title.dart
Normal file
71
lib/pages/chat_list/search_title.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class SearchTitle extends StatelessWidget {
|
||||
final String title;
|
||||
final Widget icon;
|
||||
final Widget? trailing;
|
||||
final void Function()? onTap;
|
||||
final Color? color;
|
||||
|
||||
const SearchTitle({
|
||||
required this.title,
|
||||
required this.icon,
|
||||
this.trailing,
|
||||
this.onTap,
|
||||
this.color,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Material(
|
||||
shape: Border(
|
||||
top: BorderSide(color: theme.dividerColor, width: 1),
|
||||
bottom: BorderSide(color: theme.dividerColor, width: 1),
|
||||
),
|
||||
color: color ?? theme.colorScheme.surface,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
splashColor: theme.colorScheme.surface,
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: IconTheme(
|
||||
data: theme.iconTheme.copyWith(size: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
icon,
|
||||
const SizedBox(width: 16),
|
||||
Text(
|
||||
title,
|
||||
textAlign: TextAlign.left,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.onSurface,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
if (trailing != null)
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: trailing,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
644
lib/pages/chat_list/space_view.dart
Normal file
644
lib/pages/chat_list/space_view.dart
Normal file
@@ -0,0 +1,644 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/active_call_indicator.dart';
|
||||
import 'package:tatchat/pages/chat_list/unread_bubble.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call.dart';
|
||||
import 'package:tatchat/utils/stream_extension.dart';
|
||||
import 'package:tatchat/utils/string_color.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/hover_builder.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart' as sdk;
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
enum SpaceChildAction {
|
||||
mute,
|
||||
unmute,
|
||||
markAsUnread,
|
||||
markAsRead,
|
||||
removeFromSpace,
|
||||
leave,
|
||||
}
|
||||
|
||||
enum SpaceActions { addChild, settings, leave }
|
||||
|
||||
class SpaceView extends StatefulWidget {
|
||||
final String spaceId;
|
||||
final void Function() onBack;
|
||||
final void Function(Room room) onChatTab;
|
||||
final String? activeChat;
|
||||
|
||||
const SpaceView({
|
||||
required this.spaceId,
|
||||
required this.onBack,
|
||||
required this.onChatTab,
|
||||
required this.activeChat,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
State<SpaceView> createState() => _SpaceViewState();
|
||||
}
|
||||
|
||||
class _SpaceViewState extends State<SpaceView> {
|
||||
final List<SpaceRoomsChunk$2> _discoveredChildren = [];
|
||||
final TextEditingController _filterController = TextEditingController();
|
||||
String? _nextBatch;
|
||||
bool _noMoreRooms = false;
|
||||
bool _isLoading = false;
|
||||
|
||||
StreamSubscription? _childStateSub;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
_loadHierarchy();
|
||||
_childStateSub = Matrix.of(context).client.onSync.stream
|
||||
.where(
|
||||
(syncUpdate) =>
|
||||
syncUpdate.rooms?.join?[widget.spaceId]?.timeline?.events?.any(
|
||||
(event) => event.type == EventTypes.SpaceChild,
|
||||
) ??
|
||||
false,
|
||||
)
|
||||
.listen(_loadHierarchy);
|
||||
super.initState();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_childStateSub?.cancel();
|
||||
_filterController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadHierarchy([_]) async {
|
||||
final matrix = Matrix.of(context);
|
||||
final room = matrix.client.getRoomById(widget.spaceId);
|
||||
if (room == null) return;
|
||||
|
||||
final cacheKey = 'spaces_history_cache${room.id}';
|
||||
if (_discoveredChildren.isEmpty) {
|
||||
final cachedChildren = matrix.store.getStringList(cacheKey);
|
||||
if (cachedChildren != null) {
|
||||
try {
|
||||
_discoveredChildren.addAll(
|
||||
cachedChildren.map(
|
||||
(jsonString) =>
|
||||
SpaceRoomsChunk$2.fromJson(jsonDecode(jsonString)),
|
||||
),
|
||||
);
|
||||
} catch (e, s) {
|
||||
Logs().e('Unable to json decode spaces hierarchy cache!', e, s);
|
||||
matrix.store.remove(cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final hierarchy = await room.client.getSpaceHierarchy(
|
||||
widget.spaceId,
|
||||
suggestedOnly: false,
|
||||
maxDepth: 2,
|
||||
from: _nextBatch,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (_nextBatch == null) _discoveredChildren.clear();
|
||||
_nextBatch = hierarchy.nextBatch;
|
||||
if (hierarchy.nextBatch == null) {
|
||||
_noMoreRooms = true;
|
||||
}
|
||||
_discoveredChildren.addAll(
|
||||
hierarchy.rooms.where((room) => room.roomId != widget.spaceId),
|
||||
);
|
||||
_isLoading = false;
|
||||
});
|
||||
|
||||
if (_nextBatch == null) {
|
||||
matrix.store.setStringList(
|
||||
cacheKey,
|
||||
_discoveredChildren
|
||||
.map((child) => jsonEncode(child.toJson()))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to load hierarchy', e, s);
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _joinChildRoom(SpaceRoomsChunk$2 item) async {
|
||||
final client = Matrix.of(context).client;
|
||||
final space = client.getRoomById(widget.spaceId);
|
||||
final via = space?.spaceChildren
|
||||
.firstWhereOrNull((child) => child.roomId == item.roomId)
|
||||
?.via;
|
||||
final roomResult = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () async {
|
||||
final waitForRoom = client.waitForRoomInSync(item.roomId, join: true);
|
||||
await client.joinRoom(item.roomId, via: via);
|
||||
await waitForRoom;
|
||||
return client.getRoomById(item.roomId)!;
|
||||
},
|
||||
);
|
||||
final room = roomResult.result;
|
||||
if (room != null) widget.onChatTab(room);
|
||||
}
|
||||
|
||||
Future<void> _onSpaceAction(SpaceActions action) async {
|
||||
final space = Matrix.of(context).client.getRoomById(widget.spaceId);
|
||||
|
||||
switch (action) {
|
||||
case SpaceActions.settings:
|
||||
await space?.postLoad();
|
||||
if (!mounted) return;
|
||||
context.push('/rooms/${widget.spaceId}/details');
|
||||
break;
|
||||
case SpaceActions.addChild:
|
||||
context.go('/rooms/newgroup?space_id=${widget.spaceId}');
|
||||
break;
|
||||
case SpaceActions.leave:
|
||||
final confirmed = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).areYouSure,
|
||||
message: L10n.of(context).archiveRoomDescription,
|
||||
okLabel: L10n.of(context).leave,
|
||||
cancelLabel: L10n.of(context).cancel,
|
||||
isDestructive: true,
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (confirmed != OkCancelResult.ok) return;
|
||||
|
||||
final success = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () async => await space?.leave(),
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (success.error != null) return;
|
||||
widget.onBack();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showSpaceChildEditMenu(
|
||||
BuildContext posContext,
|
||||
String roomId,
|
||||
) async {
|
||||
final client = Matrix.of(context).client;
|
||||
final space = client.getRoomById(widget.spaceId);
|
||||
final room = client.getRoomById(roomId);
|
||||
if (space == null) return;
|
||||
final overlay =
|
||||
Overlay.of(posContext).context.findRenderObject() as RenderBox;
|
||||
|
||||
final button = posContext.findRenderObject() as RenderBox;
|
||||
|
||||
final position = RelativeRect.fromRect(
|
||||
Rect.fromPoints(
|
||||
button.localToGlobal(const Offset(0, -65), ancestor: overlay),
|
||||
button.localToGlobal(
|
||||
button.size.bottomRight(Offset.zero) + const Offset(-50, 0),
|
||||
ancestor: overlay,
|
||||
),
|
||||
),
|
||||
Offset.zero & overlay.size,
|
||||
);
|
||||
|
||||
final action = await showMenu<SpaceChildAction>(
|
||||
context: posContext,
|
||||
position: position,
|
||||
items: [
|
||||
if (room != null && room.membership == Membership.join) ...[
|
||||
PopupMenuItem(
|
||||
value: room.pushRuleState == PushRuleState.notify
|
||||
? SpaceChildAction.mute
|
||||
: SpaceChildAction.unmute,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Icon(
|
||||
room.pushRuleState == PushRuleState.notify
|
||||
? Icons.notifications_off_outlined
|
||||
: Icons.notifications_on_outlined,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
room.pushRuleState == PushRuleState.notify
|
||||
? L10n.of(context).muteChat
|
||||
: L10n.of(context).unmuteChat,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: room.markedUnread
|
||||
? SpaceChildAction.markAsRead
|
||||
: SpaceChildAction.markAsUnread,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Icon(
|
||||
room.markedUnread
|
||||
? Icons.mark_as_unread
|
||||
: Icons.mark_as_unread_outlined,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
room.isUnread
|
||||
? L10n.of(context).markAsRead
|
||||
: L10n.of(context).markAsUnread,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SpaceChildAction.leave,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.delete_outlined,
|
||||
color: Theme.of(context).colorScheme.onErrorContainer,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
L10n.of(context).leave,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onErrorContainer,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
if (space.canChangeStateEvent(EventTypes.SpaceChild) == true)
|
||||
PopupMenuItem(
|
||||
value: SpaceChildAction.removeFromSpace,
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.remove,
|
||||
color: Theme.of(context).colorScheme.onErrorContainer,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text(
|
||||
L10n.of(context).removeFromSpace,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onErrorContainer,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
if (action == null) return;
|
||||
if (!mounted) return;
|
||||
switch (action) {
|
||||
case SpaceChildAction.removeFromSpace:
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: L10n.of(context).removeFromSpace,
|
||||
message: L10n.of(context).removeFromSpaceDescription,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!mounted) return;
|
||||
final result = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => space.removeSpaceChild(roomId),
|
||||
);
|
||||
if (result.isError) return;
|
||||
if (!mounted) return;
|
||||
_nextBatch = null;
|
||||
return;
|
||||
case SpaceChildAction.mute:
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room!.setPushRuleState(PushRuleState.mentionsOnly),
|
||||
);
|
||||
case SpaceChildAction.unmute:
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room!.setPushRuleState(PushRuleState.notify),
|
||||
);
|
||||
case SpaceChildAction.markAsUnread:
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room!.markUnread(true),
|
||||
);
|
||||
case SpaceChildAction.markAsRead:
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room!.markUnread(false),
|
||||
);
|
||||
case SpaceChildAction.leave:
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room!.leave(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final room = Matrix.of(context).client.getRoomById(widget.spaceId);
|
||||
final displayname =
|
||||
room?.getLocalizedDisplayname() ?? L10n.of(context).nothingFound;
|
||||
const avatarSize = Avatar.defaultSize / 1.5;
|
||||
final isAdmin = room?.canChangeStateEvent(EventTypes.SpaceChild) == true;
|
||||
return Scaffold(
|
||||
body: room == null
|
||||
? const Center(child: Icon(Icons.search_outlined, size: 80))
|
||||
: StreamBuilder(
|
||||
stream: room.client.onSync.stream
|
||||
.where((s) => s.hasRoomUpdate)
|
||||
.rateLimit(const Duration(seconds: 1)),
|
||||
builder: (context, snapshot) {
|
||||
final filter = _filterController.text.trim().toLowerCase();
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
toolbarHeight: 72,
|
||||
floating: true,
|
||||
scrolledUnderElevation: 0,
|
||||
backgroundColor: Colors.transparent,
|
||||
automaticallyImplyLeading: false,
|
||||
title: TextField(
|
||||
controller: _filterController,
|
||||
onChanged: (_) => setState(() {}),
|
||||
textInputAction: TextInputAction.search,
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.secondaryContainer,
|
||||
border: OutlineInputBorder(
|
||||
borderSide: BorderSide.none,
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
hintText: L10n.of(context).search,
|
||||
hintStyle: TextStyle(
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
floatingLabelBehavior: FloatingLabelBehavior.never,
|
||||
prefixIcon: IconButton(
|
||||
onPressed: () {},
|
||||
icon: Icon(
|
||||
Icons.search_outlined,
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
suffixIcon: PopupMenuButton<SpaceActions>(
|
||||
icon: Avatar(
|
||||
size: avatarSize,
|
||||
mxContent: room.avatar,
|
||||
name: displayname,
|
||||
shapeBorder: RoundedSuperellipseBorder(
|
||||
side: BorderSide(
|
||||
width: 1,
|
||||
color: theme.dividerColor,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius,
|
||||
),
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.spaceBorderRadius,
|
||||
),
|
||||
),
|
||||
useRootNavigator: true,
|
||||
onSelected: _onSpaceAction,
|
||||
itemBuilder: (context) => [
|
||||
if (isAdmin)
|
||||
PopupMenuItem(
|
||||
value: SpaceActions.addChild,
|
||||
child: ListTile(
|
||||
leading: Icon(Icons.edit_square),
|
||||
title: Text(
|
||||
L10n.of(context).addChatOrSubSpace,
|
||||
),
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SpaceActions.settings,
|
||||
child: ListTile(
|
||||
leading: Icon(Icons.settings_outlined),
|
||||
title: Text(L10n.of(context).settings),
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: SpaceActions.leave,
|
||||
child: ListTile(
|
||||
leading: Icon(Icons.delete_outlined),
|
||||
title: Text(L10n.of(context).leave),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverList.builder(
|
||||
itemCount: _discoveredChildren.length + 1,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == _discoveredChildren.length) {
|
||||
if (_noMoreRooms) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12.0,
|
||||
vertical: 2.0,
|
||||
),
|
||||
child: TextButton(
|
||||
onPressed: _isLoading ? null : _loadHierarchy,
|
||||
child: _isLoading
|
||||
? const CircularProgressIndicator.adaptive()
|
||||
: Text(L10n.of(context).loadMore),
|
||||
),
|
||||
);
|
||||
}
|
||||
final item = _discoveredChildren[i];
|
||||
var joinedRoom = room.client.getRoomById(item.roomId);
|
||||
final displayname =
|
||||
item.name ??
|
||||
item.canonicalAlias ??
|
||||
joinedRoom?.getLocalizedDisplayname() ??
|
||||
L10n.of(context).emptyChat;
|
||||
final avatarUrl = item.avatarUrl ?? joinedRoom?.avatar;
|
||||
if (!displayname.toLowerCase().contains(filter)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
if (joinedRoom?.membership == Membership.leave) {
|
||||
joinedRoom = null;
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 1,
|
||||
),
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppConfig.borderRadius,
|
||||
),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
color:
|
||||
joinedRoom != null &&
|
||||
widget.activeChat == joinedRoom.id
|
||||
? theme.colorScheme.secondaryContainer
|
||||
: Colors.transparent,
|
||||
child: HoverBuilder(
|
||||
builder: (context, hovered) => ListTile(
|
||||
visualDensity: const VisualDensity(
|
||||
vertical: -0.5,
|
||||
),
|
||||
contentPadding: EdgeInsets.only(
|
||||
left: 8,
|
||||
right: joinedRoom == null ? 0 : 8,
|
||||
),
|
||||
onTap: joinedRoom != null
|
||||
? () => widget.onChatTab(joinedRoom!)
|
||||
: null,
|
||||
onLongPress: joinedRoom != null
|
||||
? () => _showSpaceChildEditMenu(
|
||||
context,
|
||||
item.roomId,
|
||||
)
|
||||
: null,
|
||||
leading:
|
||||
hovered && (isAdmin || joinedRoom != null)
|
||||
? SizedBox.square(
|
||||
dimension: avatarSize,
|
||||
child: IconButton(
|
||||
splashRadius: avatarSize,
|
||||
iconSize: 14,
|
||||
style: IconButton.styleFrom(
|
||||
foregroundColor: theme
|
||||
.colorScheme
|
||||
.onTertiaryContainer,
|
||||
backgroundColor: theme
|
||||
.colorScheme
|
||||
.tertiaryContainer,
|
||||
),
|
||||
onPressed: () =>
|
||||
_showSpaceChildEditMenu(
|
||||
context,
|
||||
item.roomId,
|
||||
),
|
||||
icon: const Icon(Icons.edit_outlined),
|
||||
),
|
||||
)
|
||||
: Avatar(
|
||||
size: avatarSize,
|
||||
mxContent: avatarUrl,
|
||||
name: '#',
|
||||
backgroundColor:
|
||||
theme.colorScheme.surfaceContainer,
|
||||
textColor:
|
||||
item.name?.colorScheme.primary ??
|
||||
theme.colorScheme.onSurface,
|
||||
shapeBorder: item.roomType == 'm.space'
|
||||
? RoundedSuperellipseBorder(
|
||||
side: BorderSide(
|
||||
color: theme
|
||||
.colorScheme
|
||||
.surfaceContainerHighest,
|
||||
),
|
||||
borderRadius:
|
||||
BorderRadius.circular(
|
||||
AppConfig.borderRadius /
|
||||
4,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
borderRadius: item.roomType == 'm.space'
|
||||
? BorderRadius.circular(
|
||||
AppConfig.borderRadius / 4,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
if (joinedRoom != null &&
|
||||
joinedRoom.hasActiveMatrixRtcCall ==
|
||||
true)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
right: 4.0,
|
||||
),
|
||||
child: ActiveCallIndicator(
|
||||
room: joinedRoom,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Opacity(
|
||||
opacity: joinedRoom == null ? 0.5 : 1,
|
||||
child: Text(
|
||||
displayname,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (joinedRoom != null &&
|
||||
joinedRoom.pushRuleState !=
|
||||
PushRuleState.notify)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 4.0),
|
||||
child: Icon(
|
||||
Icons.notifications_off_outlined,
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
if (joinedRoom != null)
|
||||
UnreadBubble(room: joinedRoom)
|
||||
else
|
||||
TextButton(
|
||||
onPressed: () => _joinChildRoom(item),
|
||||
child: Text(L10n.of(context).join),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SliverPadding(padding: EdgeInsets.only(top: 32)),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
35
lib/pages/chat_list/start_chat_fab.dart
Normal file
35
lib/pages/chat_list/start_chat_fab.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class StartChatFab extends StatelessWidget {
|
||||
final bool extended;
|
||||
const StartChatFab({this.extended = false, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FloatingActionButton.extended(
|
||||
heroTag: 'start_chat_fab',
|
||||
backgroundColor: Theme.of(context).colorScheme.primary,
|
||||
foregroundColor: Theme.of(context).colorScheme.onPrimary,
|
||||
onPressed: () => context.go('/rooms/newprivatechat'),
|
||||
extendedIconLabelSpacing: extended ? 10 : 0,
|
||||
extendedPadding: extended
|
||||
? null
|
||||
: const EdgeInsets.symmetric(horizontal: 16),
|
||||
label: AnimatedSize(
|
||||
alignment: Alignment.centerLeft,
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
child: extended ? Text(L10n.of(context).newChat) : SizedBox.shrink(),
|
||||
),
|
||||
icon: const Icon(Icons.edit_square),
|
||||
);
|
||||
}
|
||||
}
|
||||
79
lib/pages/chat_list/tabs/channels_tab.dart
Normal file
79
lib/pages/chat_list/tabs/channels_tab.dart
Normal file
@@ -0,0 +1,79 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list_item.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/empty_tab_view.dart';
|
||||
import 'package:tatchat/utils/stream_extension.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
|
||||
class ChannelsTab extends StatelessWidget {
|
||||
final ChatListController controller;
|
||||
|
||||
const ChannelsTab(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final client = Matrix.of(context).client;
|
||||
final theme = Theme.of(context);
|
||||
return StreamBuilder(
|
||||
key: ValueKey(client.userID.toString()),
|
||||
stream: client.onSync.stream
|
||||
.where((s) => s.hasRoomUpdate)
|
||||
.rateLimit(const Duration(seconds: 1)),
|
||||
builder: (context, _) {
|
||||
final channels = client.rooms
|
||||
.where((room) => !room.isSpace && !room.isDirectChat)
|
||||
.toList();
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.tag_outlined,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
L10n.of(context).channels,
|
||||
style: theme.textTheme.titleLarge,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (channels.isEmpty)
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: EmptyTabView(
|
||||
icon: Icons.tag_outlined,
|
||||
title: L10n.of(context).noChannelsFound,
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverList.builder(
|
||||
itemCount: channels.length,
|
||||
itemBuilder: (context, i) {
|
||||
final room = channels[i];
|
||||
return ChatListItem(
|
||||
room,
|
||||
key: Key('channel_list_item_${room.id}'),
|
||||
onTap: () => controller.onChatTap(room),
|
||||
activeChat: controller.activeChat == room.id,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
115
lib/pages/chat_list/tabs/chat_tab_bar.dart
Normal file
115
lib/pages/chat_list/tabs/chat_tab_bar.dart
Normal file
@@ -0,0 +1,115 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/home_tab.dart';
|
||||
|
||||
class ChatTopTabBar extends StatelessWidget {
|
||||
final HomeTab currentTab;
|
||||
final ValueChanged<HomeTab> onTabSelected;
|
||||
|
||||
const ChatTopTabBar({
|
||||
super.key,
|
||||
required this.currentTab,
|
||||
required this.onTabSelected,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Material(
|
||||
color: theme.colorScheme.surfaceContainer,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border(bottom: BorderSide(color: theme.dividerColor)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
for (final tab in HomeTab.values)
|
||||
Expanded(
|
||||
child: InkWell(
|
||||
onTap: () => onTabSelected(tab),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
tab == currentTab
|
||||
? tab.selectedIcon
|
||||
: tab.icon,
|
||||
size: 20,
|
||||
color: tab == currentTab
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
tab.label(context),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: tab == currentTab
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.onSurfaceVariant,
|
||||
fontWeight: tab == currentTab
|
||||
? FontWeight.w600
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
AnimatedContainer(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
height: 3,
|
||||
color: tab == currentTab
|
||||
? theme.colorScheme.primary
|
||||
: Colors.transparent,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ChatBottomTabBar extends StatelessWidget {
|
||||
final HomeTab currentTab;
|
||||
final ValueChanged<HomeTab> onTabSelected;
|
||||
|
||||
const ChatBottomTabBar({
|
||||
super.key,
|
||||
required this.currentTab,
|
||||
required this.onTabSelected,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return NavigationBar(
|
||||
selectedIndex: currentTab.index,
|
||||
onDestinationSelected: (index) => onTabSelected(HomeTab.values[index]),
|
||||
destinations: [
|
||||
for (final tab in HomeTab.values)
|
||||
NavigationDestination(
|
||||
icon: Icon(tab.icon),
|
||||
selectedIcon: Icon(tab.selectedIcon),
|
||||
label: tab.label(context),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
56
lib/pages/chat_list/tabs/empty_tab_view.dart
Normal file
56
lib/pages/chat_list/tabs/empty_tab_view.dart
Normal file
@@ -0,0 +1,56 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class EmptyTabView extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String? description;
|
||||
|
||||
const EmptyTabView({
|
||||
super.key,
|
||||
required this.icon,
|
||||
required this.title,
|
||||
this.description,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: 96,
|
||||
color: theme.colorScheme.secondary,
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(
|
||||
title,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
color: theme.colorScheme.secondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (description != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32.0),
|
||||
child: Text(
|
||||
description!,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: theme.colorScheme.secondary),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
51
lib/pages/chat_list/tabs/home_tab.dart
Normal file
51
lib/pages/chat_list/tabs/home_tab.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
|
||||
enum HomeTab { chats, channels, spaces, murals }
|
||||
|
||||
extension HomeTabExtension on HomeTab {
|
||||
String label(BuildContext context) {
|
||||
final l10n = L10n.of(context);
|
||||
switch (this) {
|
||||
case HomeTab.chats:
|
||||
return l10n.chats;
|
||||
case HomeTab.channels:
|
||||
return l10n.channels;
|
||||
case HomeTab.spaces:
|
||||
return l10n.spaces;
|
||||
case HomeTab.murals:
|
||||
return l10n.murals;
|
||||
}
|
||||
}
|
||||
|
||||
IconData get icon {
|
||||
switch (this) {
|
||||
case HomeTab.chats:
|
||||
return Icons.forum_outlined;
|
||||
case HomeTab.channels:
|
||||
return Icons.tag_outlined;
|
||||
case HomeTab.spaces:
|
||||
return Icons.workspaces_outlined;
|
||||
case HomeTab.murals:
|
||||
return Icons.dashboard_outlined;
|
||||
}
|
||||
}
|
||||
|
||||
IconData get selectedIcon {
|
||||
switch (this) {
|
||||
case HomeTab.chats:
|
||||
return Icons.forum;
|
||||
case HomeTab.channels:
|
||||
return Icons.tag;
|
||||
case HomeTab.spaces:
|
||||
return Icons.workspaces;
|
||||
case HomeTab.murals:
|
||||
return Icons.dashboard;
|
||||
}
|
||||
}
|
||||
}
|
||||
46
lib/pages/chat_list/tabs/murals_tab.dart
Normal file
46
lib/pages/chat_list/tabs/murals_tab.dart
Normal file
@@ -0,0 +1,46 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/empty_tab_view.dart';
|
||||
|
||||
class MuralsTab extends StatelessWidget {
|
||||
const MuralsTab({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = L10n.of(context);
|
||||
return ColoredBox(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.dashboard_outlined,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(l10n.murals, style: Theme.of(context).textTheme.titleLarge),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: EmptyTabView(
|
||||
icon: Icons.dashboard_outlined,
|
||||
title: l10n.muralsComingSoon,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
89
lib/pages/chat_list/tabs/spaces_tab.dart
Normal file
89
lib/pages/chat_list/tabs/spaces_tab.dart
Normal file
@@ -0,0 +1,89 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list.dart';
|
||||
import 'package:tatchat/pages/chat_list/chat_list_item.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/empty_tab_view.dart';
|
||||
import 'package:tatchat/pages/chat_list/tabs/home_tab.dart';
|
||||
import 'package:tatchat/utils/stream_extension.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
|
||||
class SpacesTab extends StatelessWidget {
|
||||
final ChatListController controller;
|
||||
|
||||
const SpacesTab(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final client = Matrix.of(context).client;
|
||||
final theme = Theme.of(context);
|
||||
return StreamBuilder(
|
||||
key: ValueKey(client.userID.toString()),
|
||||
stream: client.onSync.stream
|
||||
.where((s) => s.hasRoomUpdate)
|
||||
.rateLimit(const Duration(seconds: 1)),
|
||||
builder: (context, _) {
|
||||
final spaces = client.rooms.where((room) => room.isSpace).toList();
|
||||
return CustomScrollView(
|
||||
slivers: [
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.workspaces_outlined,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
L10n.of(context).spaces,
|
||||
style: theme.textTheme.titleLarge,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (spaces.isEmpty)
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: EmptyTabView(
|
||||
icon: Icons.workspaces_outlined,
|
||||
title: L10n.of(context).noSpacesFound,
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverList.builder(
|
||||
itemCount: spaces.length + 1,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == spaces.length) {
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.add),
|
||||
title: Text(L10n.of(context).createNewSpace),
|
||||
onTap: () => context.go('/rooms/newspace'),
|
||||
);
|
||||
}
|
||||
final space = spaces[i];
|
||||
return ChatListItem(
|
||||
space,
|
||||
key: Key('spaces_tab_item_${space.id}'),
|
||||
activeChat: controller.activeSpaceId == space.id,
|
||||
onTap: () {
|
||||
controller.setActiveSpace(space.id);
|
||||
controller.setHomeTab(HomeTab.chats);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
55
lib/pages/chat_list/unread_bubble.dart
Normal file
55
lib/pages/chat_list/unread_bubble.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class UnreadBubble extends StatelessWidget {
|
||||
final Room room;
|
||||
const UnreadBubble({required this.room, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final unread = room.isUnread;
|
||||
final hasNotifications = room.notificationCount > 0;
|
||||
final unreadBubbleSize = unread || room.hasNewMessages
|
||||
? room.notificationCount > 0
|
||||
? 20.0
|
||||
: 14.0
|
||||
: 0.0;
|
||||
return AnimatedContainer(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
alignment: Alignment.center,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 7),
|
||||
height: unreadBubbleSize,
|
||||
width: !hasNotifications && !unread && !room.hasNewMessages
|
||||
? 0
|
||||
: (unreadBubbleSize - 9) * room.notificationCount.toString().length +
|
||||
9,
|
||||
decoration: BoxDecoration(
|
||||
color: room.highlightCount > 0 || hasNotifications
|
||||
? theme.colorScheme.tertiary
|
||||
: theme.colorScheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(unreadBubbleSize),
|
||||
),
|
||||
child: hasNotifications || room.markedUnread
|
||||
? Text(
|
||||
room.notificationCount.toString(),
|
||||
style: TextStyle(
|
||||
color: room.highlightCount > 0 || hasNotifications
|
||||
? theme.colorScheme.onTertiary
|
||||
: theme.colorScheme.onPrimaryContainer,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
textAlign: .center,
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
);
|
||||
}
|
||||
}
|
||||
120
lib/pages/chat_members/chat_members.dart
Normal file
120
lib/pages/chat_members/chat_members.dart
Normal file
@@ -0,0 +1,120 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../widgets/matrix.dart';
|
||||
import 'chat_members_view.dart';
|
||||
|
||||
class ChatMembersPage extends StatefulWidget {
|
||||
final String roomId;
|
||||
|
||||
const ChatMembersPage({required this.roomId, super.key});
|
||||
|
||||
@override
|
||||
State<ChatMembersPage> createState() => ChatMembersController();
|
||||
}
|
||||
|
||||
class ChatMembersController extends State<ChatMembersPage> {
|
||||
List<User>? members;
|
||||
List<User>? filteredMembers;
|
||||
Object? error;
|
||||
Membership membershipFilter = Membership.join;
|
||||
|
||||
final TextEditingController filterController = TextEditingController();
|
||||
|
||||
void setMembershipFilter(Membership membership) {
|
||||
membershipFilter = membership;
|
||||
setFilter();
|
||||
}
|
||||
|
||||
Future<void> setFilter([_]) async {
|
||||
final filter = filterController.text.toLowerCase().trim();
|
||||
|
||||
final members = this.members
|
||||
?.where((member) => member.membership == membershipFilter)
|
||||
.toList();
|
||||
|
||||
if (filter.isEmpty) {
|
||||
setState(() {
|
||||
filteredMembers = members
|
||||
?..sort((b, a) => a.powerLevel.level.compareTo(b.powerLevel.level));
|
||||
});
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
filteredMembers =
|
||||
members
|
||||
?.where(
|
||||
(user) =>
|
||||
user.displayName?.toLowerCase().contains(filter) ??
|
||||
user.id.toLowerCase().contains(filter),
|
||||
)
|
||||
.toList()
|
||||
?..sort((b, a) => a.powerLevel.level.compareTo(b.powerLevel.level));
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> refreshMembers([_]) async {
|
||||
Logs().d('Load room members from', widget.roomId);
|
||||
try {
|
||||
setState(() {
|
||||
error = null;
|
||||
});
|
||||
final participants = await Matrix.of(context).client
|
||||
.getRoomById(widget.roomId)
|
||||
?.requestParticipants(
|
||||
[...Membership.values]..remove(Membership.leave),
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
setState(() {
|
||||
members = participants;
|
||||
});
|
||||
setFilter();
|
||||
} catch (e, s) {
|
||||
Logs().d(
|
||||
'Unable to request participants. Try again in 3 seconds...',
|
||||
e,
|
||||
s,
|
||||
);
|
||||
setState(() {
|
||||
error = e;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
StreamSubscription? _updateSub;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
refreshMembers();
|
||||
|
||||
_updateSub = Matrix.of(context).client.onSync.stream
|
||||
.where(
|
||||
(syncUpdate) =>
|
||||
syncUpdate.rooms?.join?[widget.roomId]?.timeline?.events?.any(
|
||||
(state) => state.type == EventTypes.RoomMember,
|
||||
) ??
|
||||
false,
|
||||
)
|
||||
.listen(refreshMembers);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_updateSub?.cancel();
|
||||
filterController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ChatMembersView(this);
|
||||
}
|
||||
191
lib/pages/chat_members/chat_members_view.dart
Normal file
191
lib/pages/chat_members/chat_members_view.dart
Normal file
@@ -0,0 +1,191 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../widgets/layouts/max_width_body.dart';
|
||||
import '../../widgets/matrix.dart';
|
||||
import '../chat_details/participant_list_item.dart';
|
||||
import 'chat_members.dart';
|
||||
|
||||
class ChatMembersView extends StatelessWidget {
|
||||
final ChatMembersController controller;
|
||||
|
||||
const ChatMembersView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final room = Matrix.of(
|
||||
context,
|
||||
).client.getRoomById(controller.widget.roomId);
|
||||
if (room == null) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(L10n.of(context).oopsSomethingWentWrong)),
|
||||
body: Center(
|
||||
child: Text(L10n.of(context).youAreNoLongerParticipatingInThisChat),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final members = controller.filteredMembers;
|
||||
|
||||
final roomCount =
|
||||
(room.summary.mJoinedMemberCount ?? 0) +
|
||||
(room.summary.mInvitedMemberCount ?? 0);
|
||||
|
||||
final error = controller.error;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: const Center(child: BackButton()),
|
||||
title: Text(L10n.of(context).countParticipants(roomCount)),
|
||||
actions: [
|
||||
if (room.canInvite)
|
||||
IconButton(
|
||||
onPressed: () => context.go('/rooms/${room.id}/invite'),
|
||||
icon: const Icon(Icons.person_add_outlined),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
withScrolling: false,
|
||||
innerPadding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: error != null
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
const Icon(Icons.error_outline),
|
||||
Text(error.toLocalizedString(context)),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton.icon(
|
||||
onPressed: controller.refreshMembers,
|
||||
icon: const Icon(Icons.refresh_outlined),
|
||||
label: Text(L10n.of(context).tryAgain),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
: members == null
|
||||
? const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: CircularProgressIndicator.adaptive(),
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: members.length + 1,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == 0) {
|
||||
final availableFilters = Membership.values
|
||||
.where(
|
||||
(membership) =>
|
||||
controller.members?.any(
|
||||
(member) => member.membership == membership,
|
||||
) ??
|
||||
false,
|
||||
)
|
||||
.toList();
|
||||
availableFilters.sort(
|
||||
(a, b) => a == Membership.join ? -1 : 1,
|
||||
);
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: TextField(
|
||||
controller: controller.filterController,
|
||||
onChanged: controller.setFilter,
|
||||
decoration: InputDecoration(
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.secondaryContainer,
|
||||
border: OutlineInputBorder(
|
||||
borderSide: BorderSide.none,
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
),
|
||||
hintStyle: TextStyle(
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
prefixIcon: const Icon(Icons.search_outlined),
|
||||
hintText: L10n.of(context).search,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (availableFilters.length > 1)
|
||||
SizedBox(
|
||||
height: 64,
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: availableFilters.length,
|
||||
itemBuilder: (context, i) => Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 4.0,
|
||||
),
|
||||
child: FilterChip(
|
||||
label: Text(switch (availableFilters[i]) {
|
||||
Membership.ban => L10n.of(context).banned,
|
||||
Membership.invite =>
|
||||
L10n.of(context).countInvited(
|
||||
room.summary.mInvitedMemberCount ??
|
||||
controller.members
|
||||
?.where(
|
||||
(member) =>
|
||||
member.membership ==
|
||||
Membership.invite,
|
||||
)
|
||||
.length ??
|
||||
0,
|
||||
),
|
||||
Membership.join =>
|
||||
L10n.of(context).countParticipants(
|
||||
room.summary.mJoinedMemberCount ??
|
||||
controller.members
|
||||
?.where(
|
||||
(member) =>
|
||||
member.membership ==
|
||||
Membership.join,
|
||||
)
|
||||
.length ??
|
||||
0,
|
||||
),
|
||||
Membership.knock => L10n.of(
|
||||
context,
|
||||
).knocking,
|
||||
Membership.leave => L10n.of(
|
||||
context,
|
||||
).leftTheChat,
|
||||
}),
|
||||
selected:
|
||||
controller.membershipFilter ==
|
||||
availableFilters[i],
|
||||
onSelected: (_) => controller
|
||||
.setMembershipFilter(availableFilters[i]),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
i--;
|
||||
return ParticipantListItem(members[i]);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_permissions_settings/chat_permissions_settings_view.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:tatchat/widgets/permission_slider_dialog.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatPermissionsSettings extends StatefulWidget {
|
||||
const ChatPermissionsSettings({super.key});
|
||||
|
||||
@override
|
||||
ChatPermissionsSettingsController createState() =>
|
||||
ChatPermissionsSettingsController();
|
||||
}
|
||||
|
||||
class ChatPermissionsSettingsController extends State<ChatPermissionsSettings> {
|
||||
String? get roomId => GoRouterState.of(context).pathParameters['roomid'];
|
||||
Future<void> editPowerLevel(
|
||||
BuildContext context,
|
||||
String key,
|
||||
int currentLevel, {
|
||||
int? newLevel,
|
||||
String? category,
|
||||
}) async {
|
||||
final room = Matrix.of(context).client.getRoomById(roomId!)!;
|
||||
if (!room.canSendEvent(EventTypes.RoomPowerLevels)) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(L10n.of(context).noPermission)));
|
||||
return;
|
||||
}
|
||||
newLevel ??= await showPermissionChooser(
|
||||
context,
|
||||
currentLevel: currentLevel,
|
||||
);
|
||||
if (newLevel == null) return;
|
||||
if (!context.mounted) return;
|
||||
final content = Map<String, dynamic>.from(
|
||||
room.getState(EventTypes.RoomPowerLevels)!.content,
|
||||
);
|
||||
if (category != null) {
|
||||
if (!content.containsKey(category)) {
|
||||
content[category] = <String, dynamic>{};
|
||||
}
|
||||
content[category][key] = newLevel;
|
||||
} else {
|
||||
content[key] = newLevel;
|
||||
}
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.client.setRoomStateWithKey(
|
||||
room.id,
|
||||
EventTypes.RoomPowerLevels,
|
||||
'',
|
||||
content,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Stream get onChanged => Matrix.of(context).client.onSync.stream.where(
|
||||
(e) =>
|
||||
(e.rooms?.join?.containsKey(roomId) ?? false) &&
|
||||
(e.rooms!.join![roomId!]?.timeline?.events?.any(
|
||||
(s) => s.type == EventTypes.RoomPowerLevels,
|
||||
) ??
|
||||
false),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ChatPermissionsSettingsView(this);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_permissions_settings/chat_permissions_settings.dart';
|
||||
import 'package:tatchat/pages/chat_permissions_settings/permission_list_tile.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart';
|
||||
import 'package:tatchat/widgets/layouts/max_width_body.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatPermissionsSettingsView extends StatelessWidget {
|
||||
final ChatPermissionsSettingsController controller;
|
||||
|
||||
const ChatPermissionsSettingsView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: const Center(child: BackButton()),
|
||||
title: Text(L10n.of(context).chatPermissions),
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
child: StreamBuilder(
|
||||
stream: controller.onChanged,
|
||||
builder: (context, _) {
|
||||
final roomId = controller.roomId;
|
||||
final room = roomId == null
|
||||
? null
|
||||
: Matrix.of(context).client.getRoomById(roomId);
|
||||
if (room == null) {
|
||||
return Center(child: Text(L10n.of(context).noRoomsFound));
|
||||
}
|
||||
final powerLevelsContent = Map<String, Object?>.from(
|
||||
room.getState(EventTypes.RoomPowerLevels)?.content ?? {},
|
||||
);
|
||||
final powerLevels = Map<String, dynamic>.from(powerLevelsContent)
|
||||
..removeWhere((k, v) => v is! int);
|
||||
final eventsPowerLevels = Map<String, int?>.from(
|
||||
powerLevelsContent.tryGetMap<String, int?>('events') ?? {},
|
||||
)..removeWhere((k, v) => v is! int);
|
||||
eventsPowerLevels[MatrixRtcCallMember.eventType] ??=
|
||||
powerLevelsContent['state_default'] as int? ?? 50;
|
||||
return Column(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: const Icon(Icons.info_outlined),
|
||||
subtitle: Text(L10n.of(context).chatPermissionsDescription),
|
||||
),
|
||||
Divider(color: theme.dividerColor),
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).chatPermissions,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
for (final entry in powerLevels.entries)
|
||||
PermissionsListTile(
|
||||
permissionKey: entry.key,
|
||||
permission: entry.value,
|
||||
onChanged: (level) => controller.editPowerLevel(
|
||||
context,
|
||||
entry.key,
|
||||
entry.value,
|
||||
newLevel: level,
|
||||
),
|
||||
canEdit: room.canChangePowerLevel,
|
||||
),
|
||||
Divider(color: theme.dividerColor),
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).notifications,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
Builder(
|
||||
builder: (context) {
|
||||
const key = 'rooms';
|
||||
final value =
|
||||
powerLevelsContent.containsKey('notifications')
|
||||
? powerLevelsContent
|
||||
.tryGetMap<String, Object?>(
|
||||
'notifications',
|
||||
)
|
||||
?.tryGet<int>('rooms') ??
|
||||
0
|
||||
: 0;
|
||||
return PermissionsListTile(
|
||||
permissionKey: key,
|
||||
permission: value,
|
||||
category: 'notifications',
|
||||
canEdit: room.canChangePowerLevel,
|
||||
onChanged: (level) => controller.editPowerLevel(
|
||||
context,
|
||||
key,
|
||||
value,
|
||||
newLevel: level,
|
||||
category: 'notifications',
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
Divider(color: theme.dividerColor),
|
||||
ListTile(
|
||||
title: Text(
|
||||
L10n.of(context).configureChat,
|
||||
style: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
for (final entry in eventsPowerLevels.entries)
|
||||
PermissionsListTile(
|
||||
permissionKey: entry.key,
|
||||
category: 'events',
|
||||
permission: entry.value ?? 0,
|
||||
canEdit: room.canChangePowerLevel,
|
||||
onChanged: (level) => controller.editPowerLevel(
|
||||
context,
|
||||
entry.key,
|
||||
entry.value ?? 0,
|
||||
newLevel: level,
|
||||
category: 'events',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
130
lib/pages/chat_permissions_settings/permission_list_tile.dart
Normal file
130
lib/pages/chat_permissions_settings/permission_list_tile.dart
Normal file
@@ -0,0 +1,130 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/matrix_live_kit_calls/matrix_live_kit_call_member.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class PermissionsListTile extends StatelessWidget {
|
||||
final String permissionKey;
|
||||
final int permission;
|
||||
final String? category;
|
||||
final void Function(int? level)? onChanged;
|
||||
final bool canEdit;
|
||||
|
||||
const PermissionsListTile({
|
||||
super.key,
|
||||
required this.permissionKey,
|
||||
required this.permission,
|
||||
this.category,
|
||||
required this.onChanged,
|
||||
required this.canEdit,
|
||||
});
|
||||
|
||||
String getLocalizedPowerLevelString(BuildContext context) {
|
||||
if (category == null) {
|
||||
switch (permissionKey) {
|
||||
case 'users_default':
|
||||
return L10n.of(context).defaultPermissionLevel;
|
||||
case 'events_default':
|
||||
return L10n.of(context).sendMessages;
|
||||
case 'state_default':
|
||||
return L10n.of(context).changeGeneralChatSettings;
|
||||
case 'ban':
|
||||
return L10n.of(context).banFromChat;
|
||||
case 'kick':
|
||||
return L10n.of(context).kickFromChat;
|
||||
case 'redact':
|
||||
return L10n.of(context).deleteMessage;
|
||||
case 'invite':
|
||||
return L10n.of(context).inviteOtherUsers;
|
||||
}
|
||||
} else if (category == 'notifications') {
|
||||
switch (permissionKey) {
|
||||
case 'rooms':
|
||||
return L10n.of(context).sendRoomNotifications;
|
||||
}
|
||||
} else if (category == 'events') {
|
||||
switch (permissionKey) {
|
||||
case EventTypes.RoomName:
|
||||
return L10n.of(context).changeTheNameOfTheGroup;
|
||||
case EventTypes.RoomTopic:
|
||||
return L10n.of(context).changeTheDescriptionOfTheGroup;
|
||||
case EventTypes.RoomPowerLevels:
|
||||
return L10n.of(context).changeTheChatPermissions;
|
||||
case EventTypes.HistoryVisibility:
|
||||
return L10n.of(context).changeTheVisibilityOfChatHistory;
|
||||
case EventTypes.RoomCanonicalAlias:
|
||||
return L10n.of(context).changeTheCanonicalRoomAlias;
|
||||
case EventTypes.RoomAvatar:
|
||||
return L10n.of(context).editRoomAvatar;
|
||||
case EventTypes.RoomTombstone:
|
||||
return L10n.of(context).replaceRoomWithNewerVersion;
|
||||
case EventTypes.Encryption:
|
||||
return L10n.of(context).enableEncryption;
|
||||
case 'm.room.server_acl':
|
||||
return L10n.of(context).editBlockedServers;
|
||||
case MatrixRtcCallMember.eventType:
|
||||
return 'Create or join a group call';
|
||||
}
|
||||
}
|
||||
return permissionKey;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final color = permission >= 100
|
||||
? Colors.orangeAccent
|
||||
: permission >= 50
|
||||
? Colors.blueAccent
|
||||
: Colors.greenAccent;
|
||||
return ListTile(
|
||||
title: Text(
|
||||
getLocalizedPowerLevelString(context),
|
||||
style: theme.textTheme.titleSmall,
|
||||
),
|
||||
trailing: Material(
|
||||
color: color.withAlpha(32),
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius / 2),
|
||||
child: DropdownButton<int>(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius / 2),
|
||||
underline: const SizedBox.shrink(),
|
||||
onChanged: canEdit ? onChanged : null,
|
||||
value: permission,
|
||||
items: [
|
||||
DropdownMenuItem(
|
||||
value: permission < 50 ? permission : 0,
|
||||
child: Text(
|
||||
L10n.of(context).userLevel(permission < 50 ? permission : 0),
|
||||
),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: permission < 100 && permission >= 50 ? permission : 50,
|
||||
child: Text(
|
||||
L10n.of(context).moderatorLevel(
|
||||
permission < 100 && permission >= 50 ? permission : 50,
|
||||
),
|
||||
),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: permission >= 100 ? permission : 100,
|
||||
child: Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).adminLevel(permission >= 100 ? permission : 100),
|
||||
),
|
||||
),
|
||||
DropdownMenuItem(value: null, child: Text(L10n.of(context).custom)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
112
lib/pages/chat_search/chat_search_files_tab.dart
Normal file
112
lib/pages/chat_search/chat_search_files_tab.dart
Normal file
@@ -0,0 +1,112 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_search/search_footer.dart';
|
||||
import 'package:tatchat/utils/date_time_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/event_extension.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatSearchFilesTab extends StatelessWidget {
|
||||
final Room room;
|
||||
final List<Event> events;
|
||||
final void Function() onStartSearch;
|
||||
final bool endReached, isLoading;
|
||||
final DateTime? searchedUntil;
|
||||
|
||||
const ChatSearchFilesTab({
|
||||
required this.room,
|
||||
required this.events,
|
||||
required this.onStartSearch,
|
||||
required this.endReached,
|
||||
required this.isLoading,
|
||||
super.key,
|
||||
required this.searchedUntil,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return SelectionArea(
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
itemCount: events.length + 1,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == events.length) {
|
||||
return SearchFooter(
|
||||
searchedUntil: searchedUntil,
|
||||
endReached: endReached,
|
||||
isLoading: isLoading,
|
||||
onStartSearch: onStartSearch,
|
||||
);
|
||||
}
|
||||
final event = events[i];
|
||||
final filename =
|
||||
event.content.tryGet<String>('filename') ??
|
||||
event.content.tryGet<String>('body') ??
|
||||
L10n.of(context).unknownEvent('File');
|
||||
final filetype = (filename.contains('.')
|
||||
? filename.split('.').last.toUpperCase()
|
||||
: event.content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<String>('mimetype')
|
||||
?.toUpperCase() ??
|
||||
'UNKNOWN');
|
||||
final sizeString = event.sizeString;
|
||||
final prevEvent = i > 0 ? events[i - 1] : null;
|
||||
final sameEnvironment =
|
||||
prevEvent != null &&
|
||||
prevEvent.originServerTs.sameEnvironment(event.originServerTs);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (!sameEnvironment) ...[
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Container(height: 1, color: theme.dividerColor),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
event.originServerTs.localizedTime(context),
|
||||
style: theme.textTheme.labelSmall,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Container(height: 1, color: theme.dividerColor),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
],
|
||||
Material(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
color: theme.colorScheme.onInverseSurface,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.file_present_outlined),
|
||||
title: Text(
|
||||
filename,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
subtitle: Text('$sizeString | $filetype'),
|
||||
onTap: () => event.saveFile(context),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
129
lib/pages/chat_search/chat_search_images_tab.dart
Normal file
129
lib/pages/chat_search/chat_search_images_tab.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/pages/chat/events/video_player.dart';
|
||||
import 'package:tatchat/pages/chat_search/search_footer.dart';
|
||||
import 'package:tatchat/pages/image_viewer/image_viewer.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatSearchImagesTab extends StatelessWidget {
|
||||
final Room room;
|
||||
final List<Event> events;
|
||||
final void Function() onStartSearch;
|
||||
final bool endReached, isLoading;
|
||||
final DateTime? searchedUntil;
|
||||
|
||||
const ChatSearchImagesTab({
|
||||
required this.room,
|
||||
required this.events,
|
||||
required this.onStartSearch,
|
||||
required this.endReached,
|
||||
required this.isLoading,
|
||||
super.key,
|
||||
required this.searchedUntil,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final borderRadius = BorderRadius.circular(AppConfig.borderRadius / 2);
|
||||
final theme = Theme.of(context);
|
||||
|
||||
final eventsByMonth = <DateTime, List<Event>>{};
|
||||
for (final event in events) {
|
||||
final month = DateTime(
|
||||
event.originServerTs.year,
|
||||
event.originServerTs.month,
|
||||
);
|
||||
eventsByMonth[month] ??= [];
|
||||
eventsByMonth[month]!.add(event);
|
||||
}
|
||||
final eventsByMonthList = eventsByMonth.entries.toList();
|
||||
|
||||
const padding = 8.0;
|
||||
|
||||
return ListView.builder(
|
||||
itemCount: eventsByMonth.length + 1,
|
||||
itemBuilder: (context, i) {
|
||||
if (i == eventsByMonth.length) {
|
||||
return SearchFooter(
|
||||
searchedUntil: searchedUntil,
|
||||
endReached: endReached,
|
||||
isLoading: isLoading,
|
||||
onStartSearch: onStartSearch,
|
||||
);
|
||||
}
|
||||
|
||||
final monthEvents = eventsByMonthList[i].value;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Container(height: 1, color: theme.dividerColor),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Text(
|
||||
DateFormat.yMMMM(
|
||||
Localizations.localeOf(context).languageCode,
|
||||
).format(eventsByMonthList[i].key),
|
||||
style: theme.textTheme.labelSmall,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Container(height: 1, color: theme.dividerColor),
|
||||
),
|
||||
],
|
||||
),
|
||||
GridView.count(
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
shrinkWrap: true,
|
||||
mainAxisSpacing: padding,
|
||||
crossAxisSpacing: padding,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
padding: const EdgeInsets.all(padding),
|
||||
crossAxisCount: 3,
|
||||
children: monthEvents.map((event) {
|
||||
if (event.messageType == MessageTypes.Video) {
|
||||
return Material(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
borderRadius: borderRadius,
|
||||
child: EventVideoPlayer(event),
|
||||
);
|
||||
}
|
||||
return InkWell(
|
||||
onTap: () => showDialog(
|
||||
context: context,
|
||||
builder: (_) => ImageViewer(event, outerContext: context),
|
||||
),
|
||||
borderRadius: borderRadius,
|
||||
child: Material(
|
||||
clipBehavior: Clip.hardEdge,
|
||||
borderRadius: borderRadius,
|
||||
child: MxcImage(
|
||||
event: event,
|
||||
width: 128,
|
||||
height: 128,
|
||||
fit: BoxFit.cover,
|
||||
animated: true,
|
||||
isThumbnail: true,
|
||||
),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
147
lib/pages/chat_search/chat_search_message_tab.dart
Normal file
147
lib/pages/chat_search/chat_search_message_tab.dart
Normal file
@@ -0,0 +1,147 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_search/search_footer.dart';
|
||||
import 'package:tatchat/utils/date_time_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/utils/url_launcher.dart';
|
||||
import 'package:tatchat/widgets/avatar.dart';
|
||||
import 'package:flutter_linkify/flutter_linkify.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatSearchMessageTab extends StatelessWidget {
|
||||
final String searchQuery;
|
||||
final Room room;
|
||||
final List<Event> events;
|
||||
final void Function() onStartSearch;
|
||||
final bool endReached, isLoading;
|
||||
final DateTime? searchedUntil;
|
||||
|
||||
const ChatSearchMessageTab({
|
||||
required this.searchQuery,
|
||||
required this.room,
|
||||
required this.onStartSearch,
|
||||
required this.events,
|
||||
required this.searchedUntil,
|
||||
required this.endReached,
|
||||
required this.isLoading,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
if (events.isEmpty && searchQuery.isEmpty) {
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.search_outlined, size: 64),
|
||||
const SizedBox(height: 8),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32.0),
|
||||
child: Text(
|
||||
L10n.of(context).searchIn(
|
||||
room.getLocalizedDisplayname(MatrixLocals(L10n.of(context))),
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return SelectionArea(
|
||||
child: ListView.separated(
|
||||
itemCount: events.length + 1,
|
||||
separatorBuilder: (context, _) =>
|
||||
Divider(color: theme.dividerColor, height: 1),
|
||||
itemBuilder: (context, i) {
|
||||
if (i == events.length) {
|
||||
return SearchFooter(
|
||||
searchedUntil: searchedUntil,
|
||||
endReached: endReached,
|
||||
isLoading: isLoading,
|
||||
onStartSearch: onStartSearch,
|
||||
);
|
||||
}
|
||||
final event = events[i];
|
||||
final sender = event.senderFromMemoryOrFallback;
|
||||
final displayname = sender.calcDisplayname(
|
||||
i18n: MatrixLocals(L10n.of(context)),
|
||||
);
|
||||
return _MessageSearchResultListTile(
|
||||
sender: sender,
|
||||
displayname: displayname,
|
||||
event: event,
|
||||
room: room,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MessageSearchResultListTile extends StatelessWidget {
|
||||
const _MessageSearchResultListTile({
|
||||
required this.sender,
|
||||
required this.displayname,
|
||||
required this.event,
|
||||
required this.room,
|
||||
});
|
||||
|
||||
final User sender;
|
||||
final String displayname;
|
||||
final Event event;
|
||||
final Room room;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return ListTile(
|
||||
title: Row(
|
||||
children: [
|
||||
Avatar(mxContent: sender.avatarUrl, name: displayname, size: 16),
|
||||
const SizedBox(width: 8),
|
||||
Text(displayname),
|
||||
Expanded(
|
||||
child: Text(
|
||||
' | ${event.originServerTs.localizedTimeShort(context)}',
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
subtitle: Linkify(
|
||||
textScaleFactor: MediaQuery.textScalerOf(context).scale(1),
|
||||
options: const LinkifyOptions(humanize: false),
|
||||
linkStyle: TextStyle(
|
||||
color: theme.colorScheme.primary,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: theme.colorScheme.primary,
|
||||
),
|
||||
onOpen: (url) => UrlLauncher(context, url.url).launchUrl(),
|
||||
text: event
|
||||
.calcLocalizedBodyFallback(
|
||||
plaintextBody: true,
|
||||
removeMarkdown: true,
|
||||
MatrixLocals(L10n.of(context)),
|
||||
)
|
||||
.trim(),
|
||||
maxLines: 7,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.chevron_right_outlined),
|
||||
onPressed: () => context.go(
|
||||
'/${Uri(pathSegments: ['rooms', room.id], queryParameters: {'event': event.eventId})}',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
143
lib/pages/chat_search/chat_search_page.dart
Normal file
143
lib/pages/chat_search/chat_search_page.dart
Normal file
@@ -0,0 +1,143 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/pages/chat_search/chat_search_view.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
class ChatSearchPage extends StatefulWidget {
|
||||
final String roomId;
|
||||
const ChatSearchPage({required this.roomId, super.key});
|
||||
|
||||
@override
|
||||
ChatSearchController createState() => ChatSearchController();
|
||||
}
|
||||
|
||||
class ChatSearchController extends State<ChatSearchPage>
|
||||
with SingleTickerProviderStateMixin {
|
||||
Room? get room => Matrix.of(context).client.getRoomById(widget.roomId);
|
||||
|
||||
final TextEditingController searchController = TextEditingController();
|
||||
late final TabController tabController;
|
||||
|
||||
final List<Event> messages = [];
|
||||
final List<Event> images = [];
|
||||
final List<Event> files = [];
|
||||
String? messagesNextBatch, imagesNextBatch, filesNextBatch;
|
||||
bool messagesEndReached = false;
|
||||
bool imagesEndReached = false;
|
||||
bool filesEndReached = false;
|
||||
bool isLoading = false;
|
||||
DateTime? searchedUntil;
|
||||
|
||||
void restartSearch() {
|
||||
setState(() {
|
||||
messages.clear();
|
||||
images.clear();
|
||||
files.clear();
|
||||
messagesNextBatch = imagesNextBatch = filesNextBatch = searchedUntil =
|
||||
null;
|
||||
messagesEndReached = imagesEndReached = filesEndReached = false;
|
||||
});
|
||||
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
|
||||
startSearch();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> startSearch() async {
|
||||
switch (tabController.index) {
|
||||
case 0:
|
||||
final searchQuery = searchController.text.trim();
|
||||
if (searchQuery.isEmpty) return;
|
||||
setState(() {
|
||||
isLoading = true;
|
||||
});
|
||||
final result = await room!.searchEvents(
|
||||
searchTerm: searchController.text.trim(),
|
||||
nextBatch: messagesNextBatch,
|
||||
);
|
||||
setState(() {
|
||||
isLoading = false;
|
||||
messages.addAll(result.events);
|
||||
messagesNextBatch = result.nextBatch;
|
||||
messagesEndReached = result.nextBatch == null;
|
||||
searchedUntil = result.searchedUntil;
|
||||
});
|
||||
return;
|
||||
case 1:
|
||||
setState(() {
|
||||
isLoading = true;
|
||||
});
|
||||
final result = await room!.searchEvents(
|
||||
searchFunc: (event) => {
|
||||
MessageTypes.Image,
|
||||
MessageTypes.Video,
|
||||
}.contains(event.messageType),
|
||||
nextBatch: imagesNextBatch,
|
||||
);
|
||||
setState(() {
|
||||
isLoading = false;
|
||||
images.addAll(result.events);
|
||||
imagesNextBatch = result.nextBatch;
|
||||
imagesEndReached = result.nextBatch == null;
|
||||
searchedUntil = result.searchedUntil;
|
||||
});
|
||||
return;
|
||||
case 2:
|
||||
setState(() {
|
||||
isLoading = true;
|
||||
});
|
||||
final result = await room!.searchEvents(
|
||||
searchFunc: (event) =>
|
||||
event.messageType == MessageTypes.File ||
|
||||
(event.messageType == MessageTypes.Audio &&
|
||||
!event.content.containsKey('org.matrix.msc3245.voice')),
|
||||
nextBatch: filesNextBatch,
|
||||
);
|
||||
setState(() {
|
||||
isLoading = false;
|
||||
files.addAll(result.events);
|
||||
filesNextBatch = result.nextBatch;
|
||||
filesEndReached = result.nextBatch == null;
|
||||
searchedUntil = result.searchedUntil;
|
||||
});
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void _onTabChanged() {
|
||||
switch (tabController.index) {
|
||||
case 1:
|
||||
case 2:
|
||||
startSearch();
|
||||
break;
|
||||
case 0:
|
||||
default:
|
||||
restartSearch();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
tabController = TabController(initialIndex: 0, length: 3, vsync: this);
|
||||
tabController.addListener(_onTabChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
tabController.removeListener(_onTabChanged);
|
||||
searchController.dispose();
|
||||
tabController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ChatSearchView(this);
|
||||
}
|
||||
122
lib/pages/chat_search/chat_search_view.dart
Normal file
122
lib/pages/chat_search/chat_search_view.dart
Normal file
@@ -0,0 +1,122 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/chat_search/chat_search_files_tab.dart';
|
||||
import 'package:tatchat/pages/chat_search/chat_search_images_tab.dart';
|
||||
import 'package:tatchat/pages/chat_search/chat_search_message_tab.dart';
|
||||
import 'package:tatchat/pages/chat_search/chat_search_page.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/matrix_locals.dart';
|
||||
import 'package:tatchat/widgets/layouts/max_width_body.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class ChatSearchView extends StatelessWidget {
|
||||
final ChatSearchController controller;
|
||||
|
||||
const ChatSearchView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final room = controller.room;
|
||||
if (room == null) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(L10n.of(context).oopsSomethingWentWrong)),
|
||||
body: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(L10n.of(context).youAreNoLongerParticipatingInThisChat),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: const Center(child: BackButton()),
|
||||
titleSpacing: 0,
|
||||
title: Text(
|
||||
L10n.of(context).searchIn(
|
||||
room.getLocalizedDisplayname(MatrixLocals(L10n.of(context))),
|
||||
),
|
||||
),
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
withScrolling: false,
|
||||
child: Column(
|
||||
children: [
|
||||
if (FluffyThemes.isThreeColumnMode(context))
|
||||
const SizedBox(height: 16),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: TextField(
|
||||
controller: controller.searchController,
|
||||
onSubmitted: (_) => controller.restartSearch(),
|
||||
autofocus: true,
|
||||
enabled: controller.tabController.index == 0,
|
||||
decoration: InputDecoration(
|
||||
hintText: L10n.of(context).search,
|
||||
prefixIcon: const Icon(Icons.search_outlined),
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.secondaryContainer,
|
||||
border: OutlineInputBorder(
|
||||
borderSide: BorderSide.none,
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
),
|
||||
hintStyle: TextStyle(
|
||||
color: theme.colorScheme.onPrimaryContainer,
|
||||
fontWeight: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
TabBar(
|
||||
controller: controller.tabController,
|
||||
tabs: [
|
||||
Tab(child: Text(L10n.of(context).messages)),
|
||||
Tab(child: Text(L10n.of(context).gallery)),
|
||||
Tab(child: Text(L10n.of(context).files)),
|
||||
],
|
||||
),
|
||||
Expanded(
|
||||
child: TabBarView(
|
||||
controller: controller.tabController,
|
||||
children: [
|
||||
ChatSearchMessageTab(
|
||||
searchQuery: controller.searchController.text,
|
||||
room: room,
|
||||
onStartSearch: controller.startSearch,
|
||||
events: controller.messages,
|
||||
endReached: controller.messagesEndReached,
|
||||
isLoading: controller.isLoading,
|
||||
searchedUntil: controller.searchedUntil,
|
||||
),
|
||||
ChatSearchImagesTab(
|
||||
room: room,
|
||||
onStartSearch: controller.startSearch,
|
||||
events: controller.images,
|
||||
endReached: controller.imagesEndReached,
|
||||
isLoading: controller.isLoading,
|
||||
searchedUntil: controller.searchedUntil,
|
||||
),
|
||||
ChatSearchFilesTab(
|
||||
room: room,
|
||||
onStartSearch: controller.startSearch,
|
||||
events: controller.files,
|
||||
endReached: controller.filesEndReached,
|
||||
isLoading: controller.isLoading,
|
||||
searchedUntil: controller.searchedUntil,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
72
lib/pages/chat_search/search_footer.dart
Normal file
72
lib/pages/chat_search/search_footer.dart
Normal file
@@ -0,0 +1,72 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/utils/date_time_extension.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
class SearchFooter extends StatelessWidget {
|
||||
final DateTime? searchedUntil;
|
||||
final bool endReached, isLoading;
|
||||
final void Function() onStartSearch;
|
||||
|
||||
const SearchFooter({
|
||||
super.key,
|
||||
required this.searchedUntil,
|
||||
required this.endReached,
|
||||
required this.isLoading,
|
||||
required this.onStartSearch,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (endReached) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(L10n.of(context).noMoreResultsFound),
|
||||
),
|
||||
);
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
final searchedUntil = this.searchedUntil;
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
if (searchedUntil != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8.0),
|
||||
child: Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).chatSearchedUntil(searchedUntil.localizedTime(context)),
|
||||
style: TextStyle(fontSize: 10.5),
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
style: TextButton.styleFrom(
|
||||
backgroundColor: theme.colorScheme.secondaryContainer,
|
||||
foregroundColor: theme.colorScheme.onSecondaryContainer,
|
||||
),
|
||||
onPressed: isLoading ? null : onStartSearch,
|
||||
icon: isLoading
|
||||
? SizedBox.square(
|
||||
dimension: 18,
|
||||
child: const CircularProgressIndicator.adaptive(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.arrow_downward_outlined),
|
||||
label: Text(L10n.of(context).searchMore),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
179
lib/pages/device_settings/device_settings.dart
Normal file
179
lib/pages/device_settings/device_settings.dart
Normal file
@@ -0,0 +1,179 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:async/async.dart' show Result;
|
||||
import 'package:collection/collection.dart' show IterableExtension;
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/device_settings/device_settings_view.dart';
|
||||
import 'package:tatchat/pages/key_verification/key_verification_dialog.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_ok_cancel_alert_dialog.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_text_input_dialog.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/encryption.dart';
|
||||
import 'package:matrix/matrix.dart' hide Result;
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
import '../../widgets/matrix.dart';
|
||||
|
||||
class DevicesSettings extends StatefulWidget {
|
||||
const DevicesSettings({super.key});
|
||||
|
||||
@override
|
||||
DevicesSettingsController createState() => DevicesSettingsController();
|
||||
}
|
||||
|
||||
class DevicesSettingsController extends State<DevicesSettings> {
|
||||
List<Device>? devices;
|
||||
Future<bool> loadUserDevices(BuildContext context) async {
|
||||
if (devices != null) return true;
|
||||
devices = await Matrix.of(context).client.getDevices();
|
||||
return true;
|
||||
}
|
||||
|
||||
void reload() => setState(() => devices = null);
|
||||
|
||||
bool? chatBackupEnabled;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
_checkChatBackup();
|
||||
super.initState();
|
||||
}
|
||||
|
||||
Future<void> _checkChatBackup() async {
|
||||
final client = Matrix.of(context).client;
|
||||
final state = await client.getCryptoIdentityState();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
chatBackupEnabled = state.initialized && !state.connected;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> removeDevicesAction(List<Device> devices) async {
|
||||
final l10n = L10n.of(context);
|
||||
final matrix = Matrix.of(context);
|
||||
final client = Matrix.of(context).client;
|
||||
|
||||
final wellKnown = await Result.capture(client.getWellknown());
|
||||
final accountManageUrl = wellKnown.asValue?.value.additionalProperties
|
||||
.tryGetMap<String, Object?>('org.matrix.msc2965.authentication')
|
||||
?.tryGet<String>('account');
|
||||
if (accountManageUrl != null) {
|
||||
launchUrlString(accountManageUrl, mode: LaunchMode.inAppBrowserView);
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
if (await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: l10n.areYouSure,
|
||||
okLabel: l10n.remove,
|
||||
cancelLabel: l10n.cancel,
|
||||
message: l10n.removeDevicesDescription,
|
||||
isDestructive: true,
|
||||
) ==
|
||||
OkCancelResult.cancel) {
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
final deviceIds = <String>[];
|
||||
for (final userDevice in devices) {
|
||||
deviceIds.add(userDevice.deviceId);
|
||||
}
|
||||
|
||||
await showFutureLoadingDialog(
|
||||
context: context,
|
||||
delay: false,
|
||||
future: () => matrix.client.uiaRequestBackground(
|
||||
(auth) => matrix.client.deleteDevices(deviceIds, auth: auth),
|
||||
),
|
||||
);
|
||||
reload();
|
||||
}
|
||||
|
||||
Future<void> renameDeviceAction(Device device) async {
|
||||
final l10n = L10n.of(context);
|
||||
final matrix = Matrix.of(context);
|
||||
final displayName = await showTextInputDialog(
|
||||
context: context,
|
||||
title: l10n.changeDeviceName,
|
||||
okLabel: l10n.ok,
|
||||
cancelLabel: l10n.cancel,
|
||||
hintText: device.displayName,
|
||||
);
|
||||
if (displayName == null) return;
|
||||
if (!mounted) return;
|
||||
final success = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () =>
|
||||
matrix.client.updateDevice(device.deviceId, displayName: displayName),
|
||||
);
|
||||
if (success.error == null) {
|
||||
reload();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyDeviceAction(Device device) async {
|
||||
final l10n = L10n.of(context);
|
||||
final matrix = Matrix.of(context);
|
||||
final consent = await showOkCancelAlertDialog(
|
||||
context: context,
|
||||
title: l10n.verifyOtherDevice,
|
||||
message: l10n.verifyOtherDeviceDescription,
|
||||
okLabel: l10n.ok,
|
||||
cancelLabel: l10n.cancel,
|
||||
);
|
||||
if (consent != OkCancelResult.ok) return;
|
||||
if (!mounted) return;
|
||||
final req = await matrix
|
||||
.client
|
||||
.userDeviceKeys[matrix.client.userID!]!
|
||||
.deviceKeys[device.deviceId]!
|
||||
.startVerification();
|
||||
req.onUpdate = () {
|
||||
if ({
|
||||
KeyVerificationState.error,
|
||||
KeyVerificationState.done,
|
||||
}.contains(req.state)) {
|
||||
setState(() {});
|
||||
}
|
||||
};
|
||||
if (!mounted) return;
|
||||
await KeyVerificationDialog(request: req).show(context);
|
||||
}
|
||||
|
||||
Future<void> blockDeviceAction(Device device) async {
|
||||
final key = Matrix.of(context)
|
||||
.client
|
||||
.userDeviceKeys[Matrix.of(context).client.userID!]!
|
||||
.deviceKeys[device.deviceId]!;
|
||||
if (key.directVerified) {
|
||||
await key.setVerified(false);
|
||||
}
|
||||
await key.setBlocked(true);
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> unblockDeviceAction(Device device) async {
|
||||
final key = Matrix.of(context)
|
||||
.client
|
||||
.userDeviceKeys[Matrix.of(context).client.userID!]!
|
||||
.deviceKeys[device.deviceId]!;
|
||||
await key.setBlocked(false);
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
bool _isOwnDevice(Device userDevice) =>
|
||||
userDevice.deviceId == Matrix.of(context).client.deviceID;
|
||||
|
||||
Device? get thisDevice => devices!.firstWhereOrNull(_isOwnDevice);
|
||||
|
||||
List<Device> get notThisDevice => List<Device>.from(devices!)
|
||||
..removeWhere(_isOwnDevice)
|
||||
..sort((a, b) => (b.lastSeenTs ?? 0).compareTo(a.lastSeenTs ?? 0));
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => DevicesSettingsView(this);
|
||||
}
|
||||
148
lib/pages/device_settings/device_settings_view.dart
Normal file
148
lib/pages/device_settings/device_settings_view.dart
Normal file
@@ -0,0 +1,148 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/device_settings/device_settings.dart';
|
||||
import 'package:tatchat/widgets/layouts/max_width_body.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
import 'user_device_list_item.dart';
|
||||
|
||||
class DevicesSettingsView extends StatelessWidget {
|
||||
final DevicesSettingsController controller;
|
||||
|
||||
const DevicesSettingsView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
automaticallyImplyLeading: !FluffyThemes.isColumnMode(context),
|
||||
centerTitle: FluffyThemes.isColumnMode(context),
|
||||
title: Text(L10n.of(context).devices),
|
||||
),
|
||||
body: MaxWidthBody(
|
||||
child: FutureBuilder<bool>(
|
||||
future: controller.loadUserDevices(context),
|
||||
builder: (BuildContext context, snapshot) {
|
||||
final theme = Theme.of(context);
|
||||
if (snapshot.hasError) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: <Widget>[
|
||||
const Icon(Icons.error_outlined),
|
||||
Text(snapshot.error.toString()),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!snapshot.hasData || controller.devices == null) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator.adaptive(strokeWidth: 2),
|
||||
);
|
||||
}
|
||||
return ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: controller.notThisDevice.length + 1,
|
||||
itemBuilder: (BuildContext context, int i) {
|
||||
if (i == 0) {
|
||||
return Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
if (controller.chatBackupEnabled == false)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: ListTile(
|
||||
leading: const CircleAvatar(
|
||||
child: Icon(Icons.info_outlined),
|
||||
),
|
||||
subtitle: Text(
|
||||
L10n.of(
|
||||
context,
|
||||
).noticeChatBackupDeviceVerification,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (controller.thisDevice != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 8.0,
|
||||
),
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(
|
||||
L10n.of(context).thisDevice,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: theme.colorScheme.primary,
|
||||
),
|
||||
textAlign: TextAlign.left,
|
||||
),
|
||||
),
|
||||
UserDeviceListItem(
|
||||
controller.thisDevice!,
|
||||
rename: controller.renameDeviceAction,
|
||||
remove: (d) => controller.removeDevicesAction([d]),
|
||||
verify: controller.verifyDeviceAction,
|
||||
block: controller.blockDeviceAction,
|
||||
unblock: controller.unblockDeviceAction,
|
||||
),
|
||||
],
|
||||
if (controller.notThisDevice.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 8.0,
|
||||
),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: TextButton.icon(
|
||||
label: Text(
|
||||
L10n.of(context).removeAllOtherDevices,
|
||||
),
|
||||
style: TextButton.styleFrom(
|
||||
iconColor: theme.colorScheme.onErrorContainer,
|
||||
foregroundColor:
|
||||
theme.colorScheme.onErrorContainer,
|
||||
backgroundColor:
|
||||
theme.colorScheme.errorContainer,
|
||||
),
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
onPressed: () => controller.removeDevicesAction(
|
||||
controller.notThisDevice,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(L10n.of(context).noOtherDevicesFound),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
i--;
|
||||
return UserDeviceListItem(
|
||||
controller.notThisDevice[i],
|
||||
rename: controller.renameDeviceAction,
|
||||
remove: (d) => controller.removeDevicesAction([d]),
|
||||
verify: controller.verifyDeviceAction,
|
||||
block: controller.blockDeviceAction,
|
||||
unblock: controller.unblockDeviceAction,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
154
lib/pages/device_settings/user_device_list_item.dart
Normal file
154
lib/pages/device_settings/user_device_list_item.dart
Normal file
@@ -0,0 +1,154 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/app_config.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/widgets/adaptive_dialogs/show_modal_action_popup.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../utils/date_time_extension.dart';
|
||||
import '../../utils/matrix_sdk_extensions/device_extension.dart';
|
||||
import '../../widgets/matrix.dart';
|
||||
|
||||
enum UserDeviceListItemAction { rename, remove, verify, block, unblock }
|
||||
|
||||
class UserDeviceListItem extends StatelessWidget {
|
||||
final Device userDevice;
|
||||
final void Function(Device) remove;
|
||||
final void Function(Device) rename;
|
||||
final void Function(Device) verify;
|
||||
final void Function(Device) block;
|
||||
final void Function(Device) unblock;
|
||||
|
||||
const UserDeviceListItem(
|
||||
this.userDevice, {
|
||||
required this.remove,
|
||||
required this.rename,
|
||||
required this.verify,
|
||||
required this.block,
|
||||
required this.unblock,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final client = Matrix.of(context).client;
|
||||
final keys = client
|
||||
.userDeviceKeys[Matrix.of(context).client.userID]
|
||||
?.deviceKeys[userDevice.deviceId];
|
||||
final isOwnDevice = userDevice.deviceId == client.deviceID;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0),
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: ListTile(
|
||||
onTap: () async {
|
||||
final action = await showModalActionPopup<UserDeviceListItemAction>(
|
||||
context: context,
|
||||
title: '${userDevice.displayName} (${userDevice.deviceId})',
|
||||
cancelLabel: L10n.of(context).cancel,
|
||||
actions: [
|
||||
AdaptiveModalAction(
|
||||
value: UserDeviceListItemAction.rename,
|
||||
icon: const Icon(Icons.edit_outlined),
|
||||
label: L10n.of(context).changeDeviceName,
|
||||
),
|
||||
if (!isOwnDevice && keys != null) ...{
|
||||
AdaptiveModalAction(
|
||||
value: UserDeviceListItemAction.verify,
|
||||
icon: const Icon(Icons.verified_outlined),
|
||||
label: L10n.of(context).verifyStart,
|
||||
),
|
||||
if (!keys.blocked)
|
||||
AdaptiveModalAction(
|
||||
value: UserDeviceListItemAction.block,
|
||||
icon: const Icon(Icons.block_outlined),
|
||||
label: L10n.of(context).blockDevice,
|
||||
isDestructive: true,
|
||||
),
|
||||
if (keys.blocked)
|
||||
AdaptiveModalAction(
|
||||
value: UserDeviceListItemAction.unblock,
|
||||
icon: const Icon(Icons.block),
|
||||
label: L10n.of(context).unblockDevice,
|
||||
isDestructive: true,
|
||||
),
|
||||
},
|
||||
if (!isOwnDevice)
|
||||
AdaptiveModalAction(
|
||||
value: UserDeviceListItemAction.remove,
|
||||
icon: const Icon(Icons.delete_outlined),
|
||||
label: L10n.of(context).delete,
|
||||
isDestructive: true,
|
||||
),
|
||||
],
|
||||
);
|
||||
if (action == null) return;
|
||||
switch (action) {
|
||||
case UserDeviceListItemAction.rename:
|
||||
rename(userDevice);
|
||||
break;
|
||||
case UserDeviceListItemAction.remove:
|
||||
remove(userDevice);
|
||||
break;
|
||||
case UserDeviceListItemAction.verify:
|
||||
verify(userDevice);
|
||||
break;
|
||||
case UserDeviceListItemAction.block:
|
||||
block(userDevice);
|
||||
break;
|
||||
case UserDeviceListItemAction.unblock:
|
||||
unblock(userDevice);
|
||||
break;
|
||||
}
|
||||
},
|
||||
leading: CircleAvatar(
|
||||
foregroundColor: Colors.white,
|
||||
backgroundColor: keys == null
|
||||
? Colors.grey[700]
|
||||
: keys.blocked
|
||||
? Colors.red
|
||||
: keys.verified
|
||||
? Colors.green
|
||||
: Colors.orange,
|
||||
child: Icon(userDevice.icon),
|
||||
),
|
||||
title: Text(
|
||||
userDevice.displayname,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
subtitle: Text(
|
||||
L10n.of(context).lastActiveAgo(
|
||||
DateTime.fromMillisecondsSinceEpoch(
|
||||
userDevice.lastSeenTs ?? 0,
|
||||
).localizedTimeShort(context),
|
||||
),
|
||||
style: const TextStyle(fontWeight: FontWeight.w300),
|
||||
),
|
||||
trailing: keys == null
|
||||
? null
|
||||
: Text(
|
||||
keys.blocked
|
||||
? L10n.of(context).blocked
|
||||
: keys.verified
|
||||
? L10n.of(context).verified
|
||||
: L10n.of(context).unverified,
|
||||
style: TextStyle(
|
||||
color: keys.blocked
|
||||
? Colors.red
|
||||
: keys.verified
|
||||
? Colors.green
|
||||
: Colors.orange,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
134
lib/pages/image_viewer/image_viewer.dart
Normal file
134
lib/pages/image_viewer/image_viewer.dart
Normal file
@@ -0,0 +1,134 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/themes.dart';
|
||||
import 'package:tatchat/pages/image_viewer/image_viewer_view.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/utils/show_scaffold_dialog.dart';
|
||||
import 'package:tatchat/widgets/share_scaffold_dialog.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../utils/matrix_sdk_extensions/event_extension.dart';
|
||||
|
||||
class ImageViewer extends StatefulWidget {
|
||||
final Event event;
|
||||
final Timeline? timeline;
|
||||
final BuildContext outerContext;
|
||||
|
||||
const ImageViewer(
|
||||
this.event, {
|
||||
required this.outerContext,
|
||||
this.timeline,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
ImageViewerController createState() => ImageViewerController();
|
||||
}
|
||||
|
||||
class ImageViewerController extends State<ImageViewer> {
|
||||
final FocusNode focusNode = FocusNode();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
allEvents =
|
||||
widget.timeline?.events
|
||||
.where(
|
||||
(event) => {
|
||||
MessageTypes.Image,
|
||||
MessageTypes.Sticker,
|
||||
if (PlatformInfos.supportsVideoPlayer) MessageTypes.Video,
|
||||
}.contains(event.messageType),
|
||||
)
|
||||
.toList()
|
||||
.reversed
|
||||
.toList() ??
|
||||
[widget.event];
|
||||
var index = allEvents.indexWhere(
|
||||
(event) => event.eventId == widget.event.eventId,
|
||||
);
|
||||
if (index < 0) index = 0;
|
||||
pageController = PageController(initialPage: index);
|
||||
}
|
||||
|
||||
late final PageController pageController;
|
||||
|
||||
late final List<Event> allEvents;
|
||||
|
||||
void onKeyEvent(KeyEvent event) {
|
||||
switch (event.logicalKey) {
|
||||
case LogicalKeyboardKey.arrowUp:
|
||||
if (canGoBack) prevImage();
|
||||
break;
|
||||
case LogicalKeyboardKey.arrowDown:
|
||||
if (canGoNext) nextImage();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> prevImage() async {
|
||||
await pageController.previousPage(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
Future<void> nextImage() async {
|
||||
await pageController.nextPage(
|
||||
duration: FluffyThemes.animationDuration,
|
||||
curve: FluffyThemes.animationCurve,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
int get _index => pageController.page?.toInt() ?? 0;
|
||||
|
||||
Event get currentEvent => allEvents[_index];
|
||||
|
||||
bool get canGoNext => _index < allEvents.length - 1;
|
||||
|
||||
bool get canGoBack => _index > 0;
|
||||
|
||||
/// Forward this image to another room.
|
||||
void forwardAction() => showScaffoldDialog(
|
||||
context: context,
|
||||
builder: (context) =>
|
||||
ShareScaffoldDialog(items: [ContentShareItem(currentEvent.content)]),
|
||||
);
|
||||
|
||||
/// Save this file with a system call.
|
||||
void saveFileAction(BuildContext context) => currentEvent.saveFile(context);
|
||||
|
||||
/// Save this file with a system call.
|
||||
void shareFileAction(BuildContext context) => currentEvent.shareFile(context);
|
||||
|
||||
static const maxScaleFactor = 1.5;
|
||||
|
||||
/// Go back if user swiped it away
|
||||
void onInteractionEnds(ScaleEndDetails endDetails) {
|
||||
if (PlatformInfos.usesTouchscreen == false) {
|
||||
if (endDetails.velocity.pixelsPerSecond.dy >
|
||||
MediaQuery.sizeOf(context).height * maxScaleFactor) {
|
||||
Navigator.of(context, rootNavigator: false).pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
focusNode.dispose();
|
||||
pageController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ImageViewerView(this);
|
||||
}
|
||||
162
lib/pages/image_viewer/image_viewer_view.dart
Normal file
162
lib/pages/image_viewer/image_viewer_view.dart
Normal file
@@ -0,0 +1,162 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/image_viewer/video_player.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/hover_builder.dart';
|
||||
import 'package:tatchat/widgets/mxc_image.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import 'image_viewer.dart';
|
||||
|
||||
class ImageViewerView extends StatelessWidget {
|
||||
final ImageViewerController controller;
|
||||
|
||||
const ImageViewerView(this.controller, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final iconButtonStyle = IconButton.styleFrom(
|
||||
backgroundColor: Colors.black.withAlpha(200),
|
||||
foregroundColor: Colors.white,
|
||||
);
|
||||
return GestureDetector(
|
||||
onTap: () => Navigator.of(context).pop(),
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.black.withAlpha(128),
|
||||
extendBodyBehindAppBar: true,
|
||||
appBar: AppBar(
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
style: iconButtonStyle,
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: Navigator.of(context).pop,
|
||||
color: Colors.white,
|
||||
tooltip: L10n.of(context).close,
|
||||
),
|
||||
backgroundColor: Colors.transparent,
|
||||
actions: [
|
||||
IconButton(
|
||||
style: iconButtonStyle,
|
||||
icon: const Icon(Icons.reply_outlined),
|
||||
onPressed: controller.forwardAction,
|
||||
color: Colors.white,
|
||||
tooltip: L10n.of(context).share,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
style: iconButtonStyle,
|
||||
icon: const Icon(Icons.download_outlined),
|
||||
onPressed: () => controller.saveFileAction(context),
|
||||
color: Colors.white,
|
||||
tooltip: L10n.of(context).downloadFile,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (PlatformInfos.isMobile)
|
||||
// Use builder context to correctly position the share dialog on iPad
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 8.0),
|
||||
child: Builder(
|
||||
builder: (context) => IconButton(
|
||||
style: iconButtonStyle,
|
||||
onPressed: () => controller.shareFileAction(context),
|
||||
tooltip: L10n.of(context).share,
|
||||
color: Colors.white,
|
||||
icon: Icon(Icons.adaptive.share_outlined),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: HoverBuilder(
|
||||
builder: (context, hovered) => Stack(
|
||||
children: [
|
||||
KeyboardListener(
|
||||
focusNode: controller.focusNode,
|
||||
onKeyEvent: controller.onKeyEvent,
|
||||
child: PageView.builder(
|
||||
scrollDirection: Axis.vertical,
|
||||
controller: controller.pageController,
|
||||
itemCount: controller.allEvents.length,
|
||||
itemBuilder: (context, i) {
|
||||
final event = controller.allEvents[i];
|
||||
switch (event.messageType) {
|
||||
case MessageTypes.Video:
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 52.0),
|
||||
child: Center(
|
||||
child: GestureDetector(
|
||||
// Ignore taps to not go back here:
|
||||
onTap: () {},
|
||||
child: EventVideoPlayer(event),
|
||||
),
|
||||
),
|
||||
);
|
||||
case MessageTypes.Image:
|
||||
case MessageTypes.Sticker:
|
||||
default:
|
||||
return InteractiveViewer(
|
||||
minScale: 1.0,
|
||||
maxScale: 10.0,
|
||||
onInteractionEnd: controller.onInteractionEnds,
|
||||
child: Center(
|
||||
child: Hero(
|
||||
tag: event.eventId,
|
||||
child: GestureDetector(
|
||||
// Ignore taps to not go back here:
|
||||
onTap: () {},
|
||||
child: MxcImage(
|
||||
key: ValueKey(event.eventId),
|
||||
event: event,
|
||||
fit: BoxFit.contain,
|
||||
isThumbnail: false,
|
||||
animated: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
if (hovered)
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
children: [
|
||||
if (controller.canGoBack)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: IconButton(
|
||||
style: iconButtonStyle,
|
||||
tooltip: L10n.of(context).previous,
|
||||
icon: const Icon(Icons.arrow_upward_outlined),
|
||||
onPressed: controller.prevImage,
|
||||
),
|
||||
),
|
||||
if (controller.canGoNext)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: IconButton(
|
||||
style: iconButtonStyle,
|
||||
tooltip: L10n.of(context).next,
|
||||
icon: const Icon(Icons.arrow_downward_outlined),
|
||||
onPressed: controller.nextImage,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
191
lib/pages/image_viewer/video_player.dart
Normal file
191
lib/pages/image_viewer/video_player.dart
Normal file
@@ -0,0 +1,191 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:chewie/chewie.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/event_extension.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/blur_hash.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
|
||||
import '../../../utils/error_reporter.dart';
|
||||
import '../../widgets/mxc_image.dart';
|
||||
|
||||
class EventVideoPlayer extends StatefulWidget {
|
||||
final Event event;
|
||||
|
||||
const EventVideoPlayer(this.event, {super.key});
|
||||
|
||||
@override
|
||||
EventVideoPlayerState createState() => EventVideoPlayerState();
|
||||
}
|
||||
|
||||
class EventVideoPlayerState extends State<EventVideoPlayer> {
|
||||
ChewieController? _chewieController;
|
||||
VideoPlayerController? _videoPlayerController;
|
||||
|
||||
double? _downloadProgress;
|
||||
|
||||
// The video_player package only doesn't support Windows and Linux.
|
||||
final _supportsVideoPlayer =
|
||||
!PlatformInfos.isWindows && !PlatformInfos.isLinux;
|
||||
|
||||
Future<void> _downloadAction() async {
|
||||
if (!_supportsVideoPlayer) {
|
||||
widget.event.saveFile(context);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final fileSize = widget.event.content
|
||||
.tryGetMap<String, Object?>('info')
|
||||
?.tryGet<int>('size');
|
||||
final videoFile = await widget.event.downloadAndDecryptAttachment(
|
||||
onDownloadProgress: fileSize == null
|
||||
? null
|
||||
: (progress) {
|
||||
final progressPercentage = progress / fileSize;
|
||||
setState(() {
|
||||
_downloadProgress = progressPercentage < 1
|
||||
? progressPercentage
|
||||
: null;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Dispose the controllers if we already have them.
|
||||
_disposeControllers();
|
||||
late VideoPlayerController videoPlayerController;
|
||||
|
||||
// Create the VideoPlayerController from the contents of videoFile.
|
||||
if (kIsWeb) {
|
||||
videoPlayerController = VideoPlayerController.networkUrl(
|
||||
Uri.dataFromBytes(videoFile.bytes, mimeType: videoFile.mimeType),
|
||||
);
|
||||
} else {
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final fileNameStr =
|
||||
widget.event.attachmentMxcUrl?.pathSegments.last ??
|
||||
widget.event.body;
|
||||
final fileName = Uri.encodeComponent(fileNameStr);
|
||||
final file = File('${tempDir.path}/${fileName}_${videoFile.name}');
|
||||
if (await file.exists() == false) {
|
||||
await file.writeAsBytes(videoFile.bytes);
|
||||
}
|
||||
videoPlayerController = VideoPlayerController.file(file);
|
||||
}
|
||||
_videoPlayerController = videoPlayerController;
|
||||
|
||||
await videoPlayerController.initialize();
|
||||
|
||||
// Create a ChewieController on top.
|
||||
setState(() {
|
||||
_chewieController = ChewieController(
|
||||
videoPlayerController: videoPlayerController,
|
||||
showControlsOnInitialize: false,
|
||||
autoPlay: true,
|
||||
autoInitialize: true,
|
||||
looping: true,
|
||||
aspectRatio: _videoPlayerController?.value.aspectRatio,
|
||||
);
|
||||
});
|
||||
} on IOException catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
} catch (e, s) {
|
||||
if (!mounted) return;
|
||||
ErrorReporter(context, 'Unable to play video').onErrorCallback(e, s);
|
||||
}
|
||||
}
|
||||
|
||||
void _disposeControllers() {
|
||||
_chewieController?.dispose();
|
||||
_videoPlayerController?.dispose();
|
||||
_chewieController = null;
|
||||
_videoPlayerController = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposeControllers();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_downloadAction();
|
||||
});
|
||||
}
|
||||
|
||||
static const String fallbackBlurHash = 'L5H2EC=PM+yV0g-mq.wG9c010J}I';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasThumbnail = widget.event.hasThumbnail;
|
||||
final blurHash =
|
||||
(widget.event.infoMap as Map<String, dynamic>).tryGet<String>(
|
||||
'xyz.amorgan.blurhash',
|
||||
) ??
|
||||
fallbackBlurHash;
|
||||
final infoMap = widget.event.content.tryGetMap<String, Object?>('info');
|
||||
final videoWidth = infoMap?.tryGet<int>('w') ?? 400;
|
||||
final videoHeight = infoMap?.tryGet<int>('h') ?? 300;
|
||||
final height = MediaQuery.sizeOf(context).height - 52;
|
||||
final width = videoWidth * (height / videoHeight);
|
||||
|
||||
final chewieController = _chewieController;
|
||||
return chewieController != null
|
||||
? Center(
|
||||
child: SizedBox(
|
||||
width: width,
|
||||
height: height,
|
||||
child: Chewie(controller: chewieController),
|
||||
),
|
||||
)
|
||||
: Stack(
|
||||
children: [
|
||||
Center(
|
||||
child: Hero(
|
||||
tag: widget.event.eventId,
|
||||
child: hasThumbnail
|
||||
? MxcImage(
|
||||
event: widget.event,
|
||||
isThumbnail: true,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context) => BlurHash(
|
||||
blurhash: blurHash,
|
||||
width: width,
|
||||
height: height,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
)
|
||||
: BlurHash(
|
||||
blurhash: blurHash,
|
||||
width: width,
|
||||
height: height,
|
||||
),
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: CircularProgressIndicator.adaptive(
|
||||
value: _downloadProgress,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
38
lib/pages/intro/flows/restore_backup_flow.dart
Normal file
38
lib/pages/intro/flows/restore_backup_flow.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/utils/file_selector.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
|
||||
Future<void> restoreBackupFlow(BuildContext context) async {
|
||||
final matrix = Matrix.of(context);
|
||||
final picked = await selectFiles(context);
|
||||
final file = picked.firstOrNull;
|
||||
if (file == null) return;
|
||||
|
||||
if (!context.mounted) return;
|
||||
final result = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () async {
|
||||
final client = await matrix.getLoginClient();
|
||||
await client.database.importDump(
|
||||
String.fromCharCodes(await file.readAsBytes()),
|
||||
);
|
||||
await client.init(
|
||||
waitForFirstSync: false,
|
||||
waitUntilLoadCompletedLoaded: false,
|
||||
);
|
||||
matrix.initMatrix();
|
||||
return client.isLogged();
|
||||
},
|
||||
);
|
||||
|
||||
if (result.result == true && context.mounted) {
|
||||
context.go('/rooms');
|
||||
}
|
||||
}
|
||||
199
lib/pages/intro/intro_page.dart
Normal file
199
lib/pages/intro/intro_page.dart
Normal file
@@ -0,0 +1,199 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/intro/flows/restore_backup_flow.dart';
|
||||
import 'package:tatchat/utils/platform_infos.dart';
|
||||
import 'package:tatchat/widgets/layouts/login_scaffold.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
class IntroPage extends StatelessWidget {
|
||||
final bool isLoading, hasPresetHomeserver;
|
||||
final String? loggingInToHomeserver, welcomeText;
|
||||
final VoidCallback login, register;
|
||||
|
||||
const IntroPage({
|
||||
required this.isLoading,
|
||||
required this.loggingInToHomeserver,
|
||||
super.key,
|
||||
required this.hasPresetHomeserver,
|
||||
required this.welcomeText,
|
||||
required this.login,
|
||||
required this.register,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final addMultiAccount = Matrix.of(
|
||||
context,
|
||||
).widget.clients.any((client) => client.isLogged());
|
||||
final loggingInToHomeserver = this.loggingInToHomeserver;
|
||||
|
||||
return LoginScaffold(
|
||||
appBar: AppBar(
|
||||
centerTitle: true,
|
||||
title: addMultiAccount
|
||||
? Text(L10n.of(context).addAccount)
|
||||
: Text(AppSettings.applicationName.value),
|
||||
actions: [
|
||||
PopupMenuButton(
|
||||
useRootNavigator: true,
|
||||
itemBuilder: (_) => [
|
||||
PopupMenuItem(
|
||||
onTap: isLoading ? null : () => restoreBackupFlow(context),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
const Icon(Icons.import_export_outlined),
|
||||
Expanded(
|
||||
child: Text(
|
||||
L10n.of(context).hydrate,
|
||||
maxLines: 1,
|
||||
overflow: .ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
onTap: () => launchUrlString(AppSettings.privacyPolicy.value),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
const Icon(Icons.privacy_tip_outlined),
|
||||
Text(L10n.of(context).privacy),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
onTap: () => PlatformInfos.showDialog(context),
|
||||
child: Row(
|
||||
mainAxisSize: .min,
|
||||
spacing: 12,
|
||||
children: [
|
||||
const Icon(Icons.info_outlined),
|
||||
Text(L10n.of(context).about),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
body: isLoading
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: .center,
|
||||
children: [
|
||||
CircularProgressIndicator.adaptive(),
|
||||
if (loggingInToHomeserver != null)
|
||||
Text(L10n.of(context).logInTo(loggingInToHomeserver)),
|
||||
],
|
||||
),
|
||||
)
|
||||
: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
return SingleChildScrollView(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
minHeight: constraints.maxHeight,
|
||||
),
|
||||
child: IntrinsicHeight(
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
alignment: Alignment.center,
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Hero(
|
||||
tag: 'info-logo',
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(128),
|
||||
child: Image.asset(
|
||||
'./assets/logo/mini/logo_mini.png',
|
||||
width: 128,
|
||||
height: 128,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
L10n.of(context).appSubtitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 20),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Text(
|
||||
welcomeText ?? L10n.of(context).appDescription,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32),
|
||||
child: Column(
|
||||
mainAxisSize: .min,
|
||||
crossAxisAlignment: .stretch,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor:
|
||||
theme.colorScheme.secondary,
|
||||
foregroundColor:
|
||||
theme.colorScheme.onSecondary,
|
||||
),
|
||||
onPressed: hasPresetHomeserver
|
||||
? register
|
||||
: () => context.go(
|
||||
'${GoRouterState.of(context).uri.path}/sign_up',
|
||||
),
|
||||
child: Text(
|
||||
L10n.of(context).createNewAccount,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: login,
|
||||
child: Text(L10n.of(context).signIn),
|
||||
),
|
||||
|
||||
if (!hasPresetHomeserver)
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
final client = await Matrix.of(
|
||||
context,
|
||||
).getLoginClient();
|
||||
if (!context.mounted) return;
|
||||
context.go(
|
||||
'${GoRouterState.of(context).uri.path}/login',
|
||||
extra: client,
|
||||
);
|
||||
},
|
||||
child: Text(
|
||||
L10n.of(context).loginWithMatrixId,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 36),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
144
lib/pages/intro/intro_page_presenter.dart
Normal file
144
lib/pages/intro/intro_page_presenter.dart
Normal file
@@ -0,0 +1,144 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:tatchat/config/setting_keys.dart';
|
||||
import 'package:tatchat/pages/intro/intro_page.dart';
|
||||
import 'package:tatchat/pages/sign_in/view_model/model/public_homeserver_data.dart';
|
||||
import 'package:tatchat/utils/localized_exception_extension.dart';
|
||||
import 'package:tatchat/utils/matrix_sdk_extensions/oidc_session_json_extension.dart';
|
||||
import 'package:tatchat/utils/sign_in_flows/check_homeserver.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix_api_lite/utils/logs.dart';
|
||||
import 'package:matrix/msc_extensions/msc_2964_oidc_login_flow/msc_2964_oidc_login_flow.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:universal_html/universal_html.dart' as web;
|
||||
|
||||
class IntroPagePresenter extends StatefulWidget {
|
||||
const IntroPagePresenter({super.key});
|
||||
|
||||
@override
|
||||
State<IntroPagePresenter> createState() => _IntroPagePresenterState();
|
||||
}
|
||||
|
||||
class _IntroPagePresenterState extends State<IntroPagePresenter> {
|
||||
bool isLoading = kIsWeb;
|
||||
String? loggingInToHomeserver;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
if (kIsWeb) _finishOidcLogin();
|
||||
}
|
||||
|
||||
Future<void> _finishOidcLogin() async {
|
||||
final store = await SharedPreferences.getInstance();
|
||||
final storedHomeserverString = store.getString(
|
||||
OidcSessionJsonExtension.homeserverStoreKey,
|
||||
);
|
||||
final homeserverUrl = storedHomeserverString == null
|
||||
? null
|
||||
: Uri.tryParse(storedHomeserverString);
|
||||
|
||||
final oidcSessionString = store.getString(
|
||||
OidcSessionJsonExtension.storeKey,
|
||||
);
|
||||
final session = oidcSessionString == null
|
||||
? null
|
||||
: OidcSessionJsonExtension.fromJson(jsonDecode(oidcSessionString));
|
||||
|
||||
await store.remove(OidcSessionJsonExtension.storeKey);
|
||||
await store.remove(OidcSessionJsonExtension.homeserverStoreKey);
|
||||
if (!mounted) return;
|
||||
|
||||
if (homeserverUrl == null || session == null) {
|
||||
setState(() {
|
||||
isLoading = false;
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
loggingInToHomeserver = homeserverUrl.origin;
|
||||
});
|
||||
|
||||
try {
|
||||
final returnUrl = Uri.parse(web.window.location.href);
|
||||
final queryParameters = returnUrl.hasFragment
|
||||
? Uri.parse(returnUrl.fragment).queryParameters
|
||||
: returnUrl.queryParameters;
|
||||
final code = queryParameters['code'] as String;
|
||||
final state = queryParameters['state'] as String;
|
||||
|
||||
final client = await Matrix.of(context).getLoginClient();
|
||||
await client.checkHomeserver(homeserverUrl);
|
||||
await client.oidcLogin(session: session, code: code, state: state);
|
||||
if (!mounted) return;
|
||||
context.go('/backup');
|
||||
} catch (e, s) {
|
||||
Logs().w('Unable to login via OIDC', e, s);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(e.toLocalizedString(context))));
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _login() {
|
||||
final presetHomeserver = AppSettings.presetHomeserver.value;
|
||||
if (presetHomeserver.isEmpty) {
|
||||
context.go('${GoRouterState.of(context).uri.path}/sign_in');
|
||||
return;
|
||||
}
|
||||
|
||||
connectToHomeserverFlow(
|
||||
PublicHomeserverData(name: presetHomeserver),
|
||||
context,
|
||||
(snapshot) {},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
void _signUp() {
|
||||
final presetHomeserver = AppSettings.presetHomeserver.value;
|
||||
if (presetHomeserver.isEmpty) {
|
||||
context.go('${GoRouterState.of(context).uri.path}/sign_up');
|
||||
return;
|
||||
}
|
||||
|
||||
connectToHomeserverFlow(
|
||||
PublicHomeserverData(name: presetHomeserver),
|
||||
context,
|
||||
(snapshot) {},
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IntroPage(
|
||||
isLoading: isLoading,
|
||||
loggingInToHomeserver: loggingInToHomeserver,
|
||||
hasPresetHomeserver: AppSettings.presetHomeserver.value.isNotEmpty,
|
||||
welcomeText: AppSettings.welcomeText.value.isEmpty
|
||||
? null
|
||||
: AppSettings.welcomeText.value,
|
||||
login: _login,
|
||||
register: _signUp,
|
||||
);
|
||||
}
|
||||
}
|
||||
129
lib/pages/invitation_selection/invitation_selection.dart
Normal file
129
lib/pages/invitation_selection/invitation_selection.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
|
||||
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:tatchat/l10n/l10n.dart';
|
||||
import 'package:tatchat/pages/invitation_selection/invitation_selection_view.dart';
|
||||
import 'package:tatchat/widgets/future_loading_dialog.dart';
|
||||
import 'package:tatchat/widgets/matrix.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
|
||||
import '../../utils/localized_exception_extension.dart';
|
||||
|
||||
class InvitationSelection extends StatefulWidget {
|
||||
final String roomId;
|
||||
const InvitationSelection({super.key, required this.roomId});
|
||||
|
||||
@override
|
||||
InvitationSelectionController createState() =>
|
||||
InvitationSelectionController();
|
||||
}
|
||||
|
||||
class InvitationSelectionController extends State<InvitationSelection> {
|
||||
TextEditingController controller = TextEditingController();
|
||||
late String currentSearchTerm;
|
||||
bool loading = false;
|
||||
List<Profile> foundProfiles = [];
|
||||
Timer? coolDown;
|
||||
|
||||
String? get roomId => widget.roomId;
|
||||
|
||||
Future<List<User>> getContacts(BuildContext context) async {
|
||||
final client = Matrix.of(context).client;
|
||||
final room = client.getRoomById(roomId!)!;
|
||||
|
||||
final participants = (room.summary.mJoinedMemberCount ?? 0) > 100
|
||||
? room.getParticipants()
|
||||
: await room.requestParticipants();
|
||||
participants.removeWhere(
|
||||
(u) => ![Membership.join, Membership.invite].contains(u.membership),
|
||||
);
|
||||
final contacts = client.rooms
|
||||
.where((r) => r.isDirectChat)
|
||||
.map((r) => r.unsafeGetUserFromMemoryOrFallback(r.directChatMatrixID!))
|
||||
.toList();
|
||||
contacts.sort(
|
||||
(a, b) => a.calcDisplayname().toLowerCase().compareTo(
|
||||
b.calcDisplayname().toLowerCase(),
|
||||
),
|
||||
);
|
||||
return contacts;
|
||||
}
|
||||
|
||||
Future<void> inviteAction(
|
||||
BuildContext context,
|
||||
String id,
|
||||
String displayname,
|
||||
) async {
|
||||
final l10n = L10n.of(context);
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
final room = Matrix.of(context).client.getRoomById(roomId!)!;
|
||||
|
||||
final success = await showFutureLoadingDialog(
|
||||
context: context,
|
||||
future: () => room.invite(id),
|
||||
);
|
||||
if (success.error == null) {
|
||||
if (!context.mounted) return;
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.contactHasBeenInvitedToTheGroup)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void searchUserWithCoolDown(String text) {
|
||||
coolDown?.cancel();
|
||||
coolDown = Timer(
|
||||
const Duration(milliseconds: 500),
|
||||
() => searchUser(context, text),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> searchUser(BuildContext context, String text) async {
|
||||
coolDown?.cancel();
|
||||
if (text.isEmpty) {
|
||||
setState(() => foundProfiles = []);
|
||||
}
|
||||
currentSearchTerm = text;
|
||||
if (currentSearchTerm.isEmpty) return;
|
||||
if (loading) return;
|
||||
setState(() => loading = true);
|
||||
final matrix = Matrix.of(context);
|
||||
SearchUserDirectoryResponse response;
|
||||
try {
|
||||
response = await matrix.client.searchUserDirectory(text, limit: 10);
|
||||
} catch (e) {
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text((e).toLocalizedString(context))));
|
||||
return;
|
||||
} finally {
|
||||
setState(() => loading = false);
|
||||
}
|
||||
setState(() {
|
||||
foundProfiles = List<Profile>.from(response.results);
|
||||
if (text.isValidMatrixIdStrict() &&
|
||||
foundProfiles.indexWhere((profile) => text == profile.userId) == -1) {
|
||||
setState(
|
||||
() => foundProfiles = [
|
||||
Profile.fromJson({'user_id': text}),
|
||||
],
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => InvitationSelectionView(this);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user