summaryrefslogtreecommitdiff
path: root/lib/widgets/viewer/controls
diff options
context:
space:
mode:
authormirror <mirror@localhost>2026-11-22 08:41:00 +0900
committermirror <mirror@localhost>2026-11-22 08:41:00 +0900
commit449d8b74bd6d9dae98a07254cdfad677b920e7b0 (patch)
treec131c3528c4d517f56e19b854a7453fedb097d40 /lib/widgets/viewer/controls
downloadaves-src-master.tar.gz
aves-src-master.zip
snapshot of aves v1.13.12 (secrets removed: android/app/google-services.json)HEADv1.13.12master
Diffstat (limited to 'lib/widgets/viewer/controls')
-rw-r--r--lib/widgets/viewer/controls/cast.dart167
-rw-r--r--lib/widgets/viewer/controls/controller.dart155
-rw-r--r--lib/widgets/viewer/controls/events.dart11
-rw-r--r--lib/widgets/viewer/controls/intents.dart50
-rw-r--r--lib/widgets/viewer/controls/notifications.dart141
-rw-r--r--lib/widgets/viewer/controls/shortcuts.dart34
-rw-r--r--lib/widgets/viewer/controls/transitions.dart78
7 files changed, 636 insertions, 0 deletions
diff --git a/lib/widgets/viewer/controls/cast.dart b/lib/widgets/viewer/controls/cast.dart
new file mode 100644
index 0000000..e442fc9
--- /dev/null
+++ b/lib/widgets/viewer/controls/cast.dart
@@ -0,0 +1,167 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/props.dart';
+import 'package:aves/ref/upnp.dart';
+import 'package:aves/services/common/services.dart';
+import 'package:aves/widgets/dialogs/cast_dialog.dart';
+import 'package:collection/collection.dart';
+import 'package:dlna_dart/dlna.dart';
+import 'package:dlna_dart/xmlParser.dart';
+import 'package:flutter/material.dart';
+import 'package:network_info_plus/network_info_plus.dart';
+import 'package:shelf/shelf.dart';
+import 'package:shelf/shelf_io.dart' as shelf_io;
+import 'package:xml/xml.dart';
+
+mixin CastMixin {
+ DLNADevice? _renderer;
+ HttpServer? _mediaServer;
+
+ bool get isCasting => _renderer != null && _mediaServer != null;
+
+ Future<void> initCast(BuildContext context, List<AvesEntry> entries) async {
+ await stopCast();
+
+ final renderer = await _selectRenderer(context);
+ _renderer = renderer;
+ if (renderer == null) return;
+ debugPrint('cast: select renderer `${renderer.info.friendlyName}` at ${renderer.info.URLBase}');
+
+ final ip = await NetworkInfo().getWifiIP();
+ if (ip == null) return;
+
+ Set<String>? supportedMimeTypes;
+
+ final handler = const Pipeline().addHandler((request) async {
+ debugPrint('cast: received request for id=${request.url}');
+ final id = int.tryParse(request.url.path);
+ if (id == null) {
+ return Response.notFound('invalid url=${request.url}');
+ }
+
+ final entry = entries.firstWhereOrNull((v) => v.id == id);
+ if (entry == null) {
+ return Response.notFound('no resource for url=${request.url}');
+ }
+
+ if (supportedMimeTypes == null) {
+ // do not call `GetProtocolInfo` before serving files,
+ // as it somehow makes `Play` time out (but not `SetAVTransportURI`)
+ supportedMimeTypes = await renderer.getSinkSupportedMimeTypes();
+ debugPrint('cast: supported MIME types=$supportedMimeTypes');
+ }
+
+ // TODO TLAD [cast] transcode when MIME type is not supported by renderer
+
+ return await _sendEntry(entry);
+ });
+ _mediaServer = await shelf_io.serve(handler, ip, 8080);
+ debugPrint('cast: serving media on $_serverBaseUrl');
+ }
+
+ Future<void> stopCast() async {
+ if (isCasting) {
+ debugPrint('cast: stop');
+ }
+
+ await _mediaServer?.close();
+ _mediaServer = null;
+
+ await _renderer?.stop();
+ _renderer = null;
+ }
+
+ Future<DLNADevice?> _selectRenderer(BuildContext context) async {
+ return await showDialog<DLNADevice?>(
+ context: context,
+ builder: (context) => const CastDialog(),
+ routeSettings: const RouteSettings(name: CastDialog.routeName),
+ );
+ }
+
+ Future<void> castEntry(AvesEntry entry) async {
+ final server = _mediaServer;
+ final renderer = _renderer;
+ if (server == null || renderer == null) return;
+
+ try {
+ debugPrint('cast: set entry=$entry');
+ await renderer.setUrl(
+ '$_serverBaseUrl/${entry.id}',
+ title: entry.bestTitle ?? '',
+ type: entry.isVideo ? PlayType.Video : PlayType.Image,
+ );
+ debugPrint('cast: play entry=$entry');
+ unawaited(renderer.play());
+ } catch (e, stack) {
+ await reportService.recordError(e, stack);
+ }
+ }
+
+ String? get _serverBaseUrl {
+ final server = _mediaServer;
+ return server != null ? 'http://${server.address.host}:${server.port}' : null;
+ }
+
+ Future<Response> _sendEntry(AvesEntry entry) async {
+ // TODO TLAD [cast] providing downscaled versions is suitable when properly serving with `MediaServer`, as the renderer can pick what is best
+ final bytes = await mediaFetchService.getOriginalBytes(entry);
+
+ debugPrint('cast: send ${bytes.length} bytes for entry=$entry');
+ return Response.ok(
+ bytes,
+ headers: {
+ 'Content-Type': entry.mimeType,
+ },
+ );
+ }
+}
+
+extension ExtraDLNADevice on DLNADevice {
+ Future<String> requestCustom({
+ required String serviceId,
+ required String serviceType,
+ required String action,
+ required String data,
+ }) async {
+ return DLNAHttp.post(
+ Uri.parse(controlURL(serviceId)),
+ Map.from({
+ 'SOAPAction': '"$serviceType#$action"',
+ 'Content-Type': 'text/xml',
+ }),
+ const Utf8Encoder().convert(data),
+ );
+ }
+
+ Future<Map<String, UpnpProtocolInfo>> getProtocolInfo() async {
+ final result = await requestCustom(
+ serviceId: 'ConnectionManager',
+ serviceType: Upnp.upnpServiceTypeConnectionManager,
+ action: 'GetProtocolInfo',
+ data: Upnp.getProtocolInfoActionXml(),
+ );
+ final doc = XmlDocument.parse(result);
+ final sink = UpnpProtocolInfo(doc.findAllElements('Sink').first.innerText);
+ final source = UpnpProtocolInfo(doc.findAllElements('Source').first.innerText);
+ return {
+ 'sink': sink,
+ 'source': source,
+ };
+ }
+
+ Future<Set<String>?> getSinkSupportedMimeTypes() async {
+ final sinkProtocolInfo = (await getProtocolInfo())['sink'];
+ if (sinkProtocolInfo != null) {
+ final byProtocol = groupBy<UpnpProtocolInfoEntry, String>(sinkProtocolInfo.entries, (v) => v.protocol);
+ final httpGet = byProtocol['http-get'];
+ if (httpGet != null) {
+ return httpGet.map((v) => v.contentFormat).toSet();
+ }
+ }
+ return null;
+ }
+}
diff --git a/lib/widgets/viewer/controls/controller.dart b/lib/widgets/viewer/controls/controller.dart
new file mode 100644
index 0000000..78d55c1
--- /dev/null
+++ b/lib/widgets/viewer/controls/controller.dart
@@ -0,0 +1,155 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/services/common/services.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/viewer/controls/cast.dart';
+import 'package:aves/widgets/viewer/controls/events.dart';
+import 'package:aves_magnifier/aves_magnifier.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart';
+import 'package:leak_tracker/leak_tracker.dart';
+
+class ViewerController with CastMixin {
+ final ValueNotifier<AvesEntry?> entryNotifier = ValueNotifier(null);
+ final ViewerTransition transition;
+ final Duration? autopilotInterval;
+ final bool autopilotAnimatedZoom;
+ final bool repeat;
+
+ late final ScaleLevel _initialScale;
+ late final ValueNotifier<bool> _autopilotNotifier;
+ Timer? _playTimer;
+ final StreamController _streamController = StreamController.broadcast();
+ final Map<TickerProvider, _AutopilotAnimators> _autopilotAnimators = {};
+ ScaleLevel? _autopilotInitialScale;
+
+ Stream<dynamic> get _events => _streamController.stream;
+
+ Stream<ViewerShowNextEvent> get showNextCommands => _events.where((event) => event is ViewerShowNextEvent).cast<ViewerShowNextEvent>();
+
+ Stream<ViewerOverlayToggleEvent> get overlayCommands => _events.where((event) => event is ViewerOverlayToggleEvent).cast<ViewerOverlayToggleEvent>();
+
+ bool get autopilot => _autopilotNotifier.value;
+
+ set autopilot(bool enabled) => _autopilotNotifier.value = enabled;
+
+ ScaleLevel get initialScale => _autopilotInitialScale ?? _initialScale;
+
+ static final _autopilotScaleTweens = [
+ Tween<double>(begin: 1, end: 1.2),
+ Tween<double>(begin: 1.2, end: 1),
+ ];
+
+ ViewerController({
+ ScaleLevel initialScale = const ScaleLevel(ref: ScaleReference.contained),
+ this.transition = ViewerTransition.parallax,
+ this.repeat = false,
+ bool autopilot = false,
+ this.autopilotInterval,
+ this.autopilotAnimatedZoom = false,
+ }) {
+ if (kFlutterMemoryAllocationsEnabled) {
+ LeakTracking.dispatchObjectCreated(
+ library: 'aves',
+ className: '$ViewerController',
+ object: this,
+ );
+ }
+ _initialScale = initialScale;
+ entryNotifier.addListener(_onEntryChanged);
+ _autopilotNotifier = ValueNotifier(autopilot);
+ _autopilotNotifier.addListener(_onAutopilotChanged);
+ _onAutopilotChanged();
+ }
+
+ void dispose() {
+ if (kFlutterMemoryAllocationsEnabled) {
+ LeakTracking.dispatchObjectDisposed(object: this);
+ }
+ entryNotifier.removeListener(_onEntryChanged);
+ windowService.setColorMode(wideColorGamut: false, hdr: false);
+ _autopilotNotifier.dispose();
+ _clearAutopilotAnimations();
+ _stopPlayTimer();
+ _streamController.close();
+ }
+
+ Future<void> _onEntryChanged() async {
+ if (await windowService.supportsHdr()) {
+ await windowService.setColorMode(
+ wideColorGamut: false,
+ hdr: entryNotifier.value?.isHdr ?? false,
+ );
+ }
+ }
+
+ void _onAutopilotChanged() {
+ _clearAutopilotAnimations();
+ _stopPlayTimer();
+ if (autopilot && autopilotInterval != null) {
+ _playTimer = Timer.periodic(autopilotInterval!, (_) => _streamController.add(ViewerShowNextEvent()));
+ _streamController.add(const ViewerOverlayToggleEvent(visible: false));
+ }
+ }
+
+ void _stopPlayTimer() => _playTimer?.cancel();
+
+ void _clearAutopilotAnimations() => _autopilotAnimators.keys.toSet().forEach((v) => stopAutopilotAnimation(vsync: v));
+
+ void stopAutopilotAnimation({required TickerProvider vsync}) {
+ final animationController = _autopilotAnimators.remove(vsync);
+ return animationController?.dispose();
+ }
+
+ void startAutopilotAnimation({
+ required TickerProvider vsync,
+ required void Function({required ScaleLevel scaleLevel}) onUpdate,
+ }) {
+ stopAutopilotAnimation(vsync: vsync);
+ if (!autopilot || !autopilotAnimatedZoom) return;
+
+ final scaleLevelRef = _initialScale.ref;
+ final scaleFactorTween = _autopilotScaleTweens[Random().nextInt(_autopilotScaleTweens.length)];
+ _autopilotInitialScale = ScaleLevel(ref: scaleLevelRef, factor: scaleFactorTween.begin!);
+
+ final animationController = AnimationController(
+ duration: autopilotInterval,
+ vsync: vsync,
+ );
+ final animation = CurvedAnimation(
+ parent: animationController,
+ curve: Curves.linear,
+ );
+ animationController.addListener(() {
+ return onUpdate.call(
+ scaleLevel: ScaleLevel(
+ ref: scaleLevelRef,
+ factor: scaleFactorTween.evaluate(animation),
+ ),
+ );
+ });
+ _autopilotAnimators[vsync] = _AutopilotAnimators(
+ controller: animationController,
+ animation: animation,
+ );
+ Future.delayed(ADurations.viewerHorizontalPageAnimation).then((_) => _autopilotAnimators[vsync]?.controller.forward());
+ }
+}
+
+class _AutopilotAnimators {
+ final AnimationController controller;
+ final CurvedAnimation animation;
+
+ _AutopilotAnimators({
+ required this.controller,
+ required this.animation,
+ });
+
+ void dispose() {
+ animation.dispose();
+ controller.dispose();
+ }
+}
diff --git a/lib/widgets/viewer/controls/events.dart b/lib/widgets/viewer/controls/events.dart
new file mode 100644
index 0000000..e39c97e
--- /dev/null
+++ b/lib/widgets/viewer/controls/events.dart
@@ -0,0 +1,11 @@
+import 'package:flutter/foundation.dart';
+
+@immutable
+class ViewerShowNextEvent {}
+
+@immutable
+class ViewerOverlayToggleEvent {
+ final bool? visible;
+
+ const ViewerOverlayToggleEvent({required this.visible});
+}
diff --git a/lib/widgets/viewer/controls/intents.dart b/lib/widgets/viewer/controls/intents.dart
new file mode 100644
index 0000000..66c76de
--- /dev/null
+++ b/lib/widgets/viewer/controls/intents.dart
@@ -0,0 +1,50 @@
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/widgets.dart';
+
+class ShowPreviousIntent extends Intent {
+ const ShowPreviousIntent();
+}
+
+class ShowNextIntent extends Intent {
+ const ShowNextIntent();
+}
+
+class LeaveIntent extends Intent {
+ const LeaveIntent();
+}
+
+class ShowInfoIntent extends Intent {
+ const ShowInfoIntent();
+}
+
+class TvShowLessInfoIntent extends Intent {
+ const TvShowLessInfoIntent();
+}
+
+class TvShowMoreInfoIntent extends Intent {
+ const TvShowMoreInfoIntent();
+}
+
+class PlayPauseIntent extends Intent {
+ final TvPlayPauseType type;
+
+ const PlayPauseIntent.play() : type = TvPlayPauseType.play;
+
+ const PlayPauseIntent.pause() : type = TvPlayPauseType.pause;
+
+ const PlayPauseIntent.toggle() : type = TvPlayPauseType.toggle;
+}
+
+enum TvPlayPauseType {
+ play,
+ pause,
+ toggle,
+}
+
+class EntryActionIntent extends Intent {
+ final EntryAction action;
+
+ const EntryActionIntent({
+ required this.action,
+ });
+}
diff --git a/lib/widgets/viewer/controls/notifications.dart b/lib/widgets/viewer/controls/notifications.dart
new file mode 100644
index 0000000..29ac67f
--- /dev/null
+++ b/lib/widgets/viewer/controls/notifications.dart
@@ -0,0 +1,141 @@
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/filters/filters.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:aves_video/aves_video.dart';
+import 'package:equatable/equatable.dart';
+import 'package:flutter/widgets.dart';
+
+@immutable
+class LockViewNotification extends Notification {
+ final bool locked;
+
+ const LockViewNotification({required this.locked});
+}
+
+@immutable
+class PopVisualNotification extends Notification {}
+
+@immutable
+class ShowImageNotification extends Notification {}
+
+@immutable
+class ShowInfoPageNotification extends Notification {}
+
+@immutable
+class ShowPreviousEntryNotification extends Notification {
+ final bool animate;
+
+ const ShowPreviousEntryNotification({required this.animate});
+}
+
+@immutable
+class ShowNextEntryNotification extends Notification {
+ final bool animate;
+
+ const ShowNextEntryNotification({required this.animate});
+}
+
+@immutable
+class ShowEntryNotification extends Notification {
+ final bool animate;
+ final int index;
+
+ const ShowEntryNotification({
+ required this.animate,
+ required this.index,
+ });
+}
+
+@immutable
+class ShowPreviousVideoNotification extends Notification {}
+
+@immutable
+class ShowNextVideoNotification extends Notification {}
+
+@immutable
+class ToggleOverlayNotification extends Notification {
+ final bool? visible;
+
+ const ToggleOverlayNotification({this.visible});
+}
+
+@immutable
+class TvShowLessInfoNotification extends Notification {}
+
+@immutable
+class TvShowMoreInfoNotification extends Notification {}
+
+@immutable
+class VideoActionNotification extends Notification {
+ final AvesVideoController controller;
+ final AvesEntry entry;
+ final EntryAction action;
+
+ const VideoActionNotification({
+ required this.controller,
+ required this.entry,
+ required this.action,
+ });
+}
+
+@immutable
+class CastNotification extends Notification with EquatableMixin {
+ final bool enabled;
+
+ @override
+ List<Object?> get props => [enabled];
+
+ const CastNotification(this.enabled);
+}
+
+@immutable
+class SelectFilterNotification extends Notification with EquatableMixin {
+ final CollectionFilter filter;
+
+ @override
+ List<Object?> get props => [filter];
+
+ const SelectFilterNotification(this.filter);
+}
+
+@immutable
+class DecomposeFilterNotification extends Notification with EquatableMixin {
+ final CollectionFilter filter;
+
+ @override
+ List<Object?> get props => [filter];
+
+ const DecomposeFilterNotification(this.filter);
+}
+
+@immutable
+class EntryDeletedNotification extends Notification with EquatableMixin {
+ final Set<AvesEntry> entries;
+
+ @override
+ List<Object?> get props => [entries];
+
+ const EntryDeletedNotification(this.entries);
+}
+
+@immutable
+class EntryMovedNotification extends Notification with EquatableMixin {
+ final MoveType moveType;
+ final Set<AvesEntry> entries;
+
+ @override
+ List<Object?> get props => [moveType, entries];
+
+ const EntryMovedNotification(this.moveType, this.entries);
+}
+
+@immutable
+class FullImageLoadedNotification extends Notification {
+ final AvesEntry entry;
+ final ImageProvider image;
+
+ const FullImageLoadedNotification(this.entry, this.image);
+}
+
+@immutable
+class PopupMenuOpenedNotification extends Notification {}
diff --git a/lib/widgets/viewer/controls/shortcuts.dart b/lib/widgets/viewer/controls/shortcuts.dart
new file mode 100644
index 0000000..25c0b0a
--- /dev/null
+++ b/lib/widgets/viewer/controls/shortcuts.dart
@@ -0,0 +1,34 @@
+import 'package:aves/widgets/viewer/controls/intents.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+
+class ViewerShortcuts {
+ static const entryActions = {
+ SingleActivator(LogicalKeyboardKey.delete): EntryActionIntent(action: EntryAction.delete),
+ };
+
+// cf https://developer.android.com/training/tv/start/controllers#media-events
+ static const media = {
+ // KEYCODE_MEDIA_PLAY_PAUSE / 85 / play/pause
+ SingleActivator(LogicalKeyboardKey.mediaPlayPause): PlayPauseIntent.toggle(),
+ // KEYCODE_MEDIA_STOP / 86 / stop
+ SingleActivator(LogicalKeyboardKey.mediaStop): PlayPauseIntent.pause(),
+ // KEYCODE_MEDIA_NEXT / 87 / skip to next
+ SingleActivator(LogicalKeyboardKey.mediaTrackNext): ShowNextIntent(),
+ // KEYCODE_MEDIA_PREVIOUS / 88 / skip to previous
+ SingleActivator(LogicalKeyboardKey.mediaTrackPrevious): ShowPreviousIntent(),
+ // KEYCODE_MEDIA_PLAY / 126 / play
+ SingleActivator(LogicalKeyboardKey.mediaPlay): PlayPauseIntent.play(),
+ // KEYCODE_MEDIA_PAUSE / 127 / pause
+ SingleActivator(LogicalKeyboardKey.mediaPause): PlayPauseIntent.pause(),
+ // KEYCODE_BUTTON_L1 / 102 / skip to previous
+ SingleActivator(LogicalKeyboardKey.gameButtonLeft1): ShowPreviousIntent(),
+ // KEYCODE_BUTTON_R1 / 103 / skip to next
+ SingleActivator(LogicalKeyboardKey.gameButtonRight1): ShowNextIntent(),
+ // KEYCODE_BUTTON_START / 108 / pause
+ SingleActivator(LogicalKeyboardKey.gameButtonStart): PlayPauseIntent.pause(),
+ // KEYCODE_BUTTON_SELECT / 109 / play/pause
+ SingleActivator(LogicalKeyboardKey.gameButtonSelect): PlayPauseIntent.toggle(),
+ };
+}
diff --git a/lib/widgets/viewer/controls/transitions.dart b/lib/widgets/viewer/controls/transitions.dart
new file mode 100644
index 0000000..0adf9b8
--- /dev/null
+++ b/lib/widgets/viewer/controls/transitions.dart
@@ -0,0 +1,78 @@
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:flutter/widgets.dart';
+
+class PageTransitionEffects {
+ static TransitionBuilder fade(
+ PageController pageController,
+ int index, {
+ required bool zoomIn,
+ }) =>
+ (context, child) {
+ double opacity = 0;
+ double dx = 0;
+ double scale = 1;
+ if (pageController.hasClients && pageController.position.haveDimensions) {
+ final position = (pageController.page! - index).clamp(-1.0, 1.0);
+ final width = pageController.position.viewportDimension;
+ opacity = (1 - position.abs()).clamp(0, 1);
+ dx = position * width * (context.isRtl ? -1 : 1);
+ if (zoomIn) {
+ scale = 1 + position;
+ }
+ }
+ return Opacity(
+ opacity: opacity,
+ child: Transform.translate(
+ offset: Offset(dx, 0),
+ child: Transform.scale(
+ scale: scale,
+ child: child,
+ ),
+ ),
+ );
+ };
+
+ static TransitionBuilder slide(
+ PageController pageController,
+ int index, {
+ required bool parallax,
+ }) =>
+ (context, child) {
+ double dx = 0;
+ if (pageController.hasClients && pageController.position.haveDimensions) {
+ final position = (pageController.page! - index).clamp(-1.0, 1.0);
+ final width = pageController.position.viewportDimension;
+ if (parallax) {
+ dx = position * width / 2 * (context.isRtl ? -1 : 1);
+ }
+ }
+ return ClipRect(
+ child: Transform.translate(
+ offset: Offset(dx, 0),
+ child: child,
+ ),
+ );
+ };
+
+ static TransitionBuilder none(
+ PageController pageController,
+ int index,
+ ) =>
+ (context, child) {
+ double opacity = 0;
+ double dx = 0;
+ if (pageController.hasClients && pageController.position.haveDimensions) {
+ final position = (pageController.page! - index).clamp(-1.0, 1.0);
+ final width = pageController.position.viewportDimension;
+ opacity = (1 - position.abs()).roundToDouble().clamp(0, 1);
+ dx = position * width * (context.isRtl ? -1 : 1);
+ }
+ return Opacity(
+ opacity: opacity,
+ child: Transform.translate(
+ offset: Offset(dx, 0),
+ child: child,
+ ),
+ );
+ };
+}