summaryrefslogtreecommitdiff
path: root/lib/widgets/viewer/visual
diff options
context:
space:
mode:
Diffstat (limited to 'lib/widgets/viewer/visual')
-rw-r--r--lib/widgets/viewer/visual/controller_mixin.dart274
-rw-r--r--lib/widgets/viewer/visual/entry_page_view.dart551
-rw-r--r--lib/widgets/viewer/visual/error.dart60
-rw-r--r--lib/widgets/viewer/visual/raster.dart517
-rw-r--r--lib/widgets/viewer/visual/vector.dart443
-rw-r--r--lib/widgets/viewer/visual/video/cover.dart164
-rw-r--r--lib/widgets/viewer/visual/video/subtitle/ass_parser.dart559
-rw-r--r--lib/widgets/viewer/visual/video/subtitle/line.dart40
-rw-r--r--lib/widgets/viewer/visual/video/subtitle/span.dart35
-rw-r--r--lib/widgets/viewer/visual/video/subtitle/style.dart101
-rw-r--r--lib/widgets/viewer/visual/video/subtitle/subtitle.dart337
-rw-r--r--lib/widgets/viewer/visual/video/swipe_action.dart137
-rw-r--r--lib/widgets/viewer/visual/video/video_view.dart61
13 files changed, 3279 insertions, 0 deletions
diff --git a/lib/widgets/viewer/visual/controller_mixin.dart b/lib/widgets/viewer/visual/controller_mixin.dart
new file mode 100644
index 0000000..f96ed8f
--- /dev/null
+++ b/lib/widgets/viewer/visual/controller_mixin.dart
@@ -0,0 +1,274 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:aves/app_mode.dart';
+import 'package:aves/model/device.dart';
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/multipage.dart';
+import 'package:aves/model/entry/extensions/props.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/services/common/services.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/viewer/multipage/conductor.dart';
+import 'package:aves/widgets/viewer/multipage/controller.dart';
+import 'package:aves/widgets/viewer/video/conductor.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:aves_video/aves_video.dart';
+import 'package:collection/collection.dart';
+import 'package:floating/floating.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/scheduler.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+
+// state controllers/monitors
+mixin EntryViewControllerMixin<T extends StatefulWidget> on State<T> {
+ final Map<AvesEntry, VoidCallback> _metadataChangeListeners = {};
+ final Map<MultiPageController, Future<void> Function()> _multiPageControllerPageListeners = {};
+
+ bool? videoMutedOverride;
+
+ bool get isViewingImage;
+
+ ValueNotifier<AvesEntry?> get entryNotifier;
+
+ Future<void> initEntryControllers(AvesEntry? entry) async {
+ if (!mounted || entry == null) return;
+
+ if (entry.isVideo) {
+ await _initVideoController(entry);
+ }
+ if (entry.isMultiPage) {
+ await _initMultiPageController(entry);
+ }
+ void listener() => _onMetadataChanged(entry);
+ _metadataChangeListeners[entry] = listener;
+ entry.metadataChangeNotifier.addListener(listener);
+ }
+
+ void cleanEntryControllers(AvesEntry? entry) {
+ if (entry == null) return;
+
+ final listener = _metadataChangeListeners.remove(entry);
+ if (listener != null) {
+ entry.metadataChangeNotifier.removeListener(listener);
+ }
+ if (entry.isMultiPage) {
+ _cleanMultiPageController(entry);
+ }
+ }
+
+ void _onMetadataChanged(AvesEntry entry) {
+ debugPrint('reinitialize controllers for entry=$entry because metadata changed');
+ cleanEntryControllers(entry);
+ initEntryControllers(entry);
+ }
+
+ SlideshowVideoPlayback? get videoPlaybackOverride {
+ if (!mounted) return null;
+ final appMode = context.read<ValueNotifier<AppMode>>().value;
+ switch (appMode) {
+ case AppMode.screenSaver:
+ return settings.screenSaverVideoPlayback;
+ case AppMode.slideshow:
+ return settings.slideshowVideoPlayback;
+ default:
+ return null;
+ }
+ }
+
+ bool get videoAutoPlayEnabled {
+ if (!isViewingImage) return false;
+
+ switch (videoPlaybackOverride) {
+ case SlideshowVideoPlayback.skip:
+ return false;
+ case SlideshowVideoPlayback.playMuted:
+ case SlideshowVideoPlayback.playWithSound:
+ return true;
+ case null:
+ break;
+ }
+
+ switch (settings.videoAutoPlayMode) {
+ case VideoAutoPlayMode.disabled:
+ return false;
+ case VideoAutoPlayMode.playMuted:
+ case VideoAutoPlayMode.playWithSound:
+ return true;
+ }
+ }
+
+ bool get shouldAutoPlayVideoMuted {
+ if (videoMutedOverride != null) {
+ return videoMutedOverride!;
+ }
+
+ switch (videoPlaybackOverride) {
+ case SlideshowVideoPlayback.skip:
+ case SlideshowVideoPlayback.playWithSound:
+ return false;
+ case SlideshowVideoPlayback.playMuted:
+ return true;
+ case null:
+ break;
+ }
+
+ switch (settings.videoAutoPlayMode) {
+ case VideoAutoPlayMode.disabled:
+ case VideoAutoPlayMode.playWithSound:
+ return false;
+ case VideoAutoPlayMode.playMuted:
+ return true;
+ }
+ }
+
+ bool get shouldAutoPlayMotionPhoto {
+ if (!isViewingImage) return false;
+
+ return settings.enableMotionPhotoAutoPlay;
+ }
+
+ Future<void> _initVideoController(AvesEntry entry) async {
+ final controller = await context.read<VideoConductor>().getOrCreateController(entry);
+ setState(() {});
+
+ if (videoAutoPlayEnabled || entry.isAnimated) {
+ final resumeTimeMillis = await controller.getResumeTime(context);
+ await _autoPlayVideo(controller, () => entry == entryNotifier.value, resumeTimeMillis: resumeTimeMillis);
+ }
+ }
+
+ Future<void> _initMultiPageController(AvesEntry entry) async {
+ if (!mounted) return;
+
+ final multiPageController = context.read<MultiPageConductor>().getOrCreateController(entry);
+ setState(() {});
+
+ final multiPageInfo = multiPageController.info ?? await multiPageController.infoStream.first;
+ assert(multiPageInfo != null);
+ if (multiPageInfo == null) return;
+
+ if (entry.isMotionPhoto) {
+ await multiPageInfo.extractMotionPhotoVideo();
+ }
+
+ final videoPageEntries = multiPageInfo.videoPageEntries;
+ if (videoPageEntries.isNotEmpty) {
+ // init video controllers for all pages that could need it
+ final videoConductor = context.read<VideoConductor>();
+ await Future.forEach(videoPageEntries, (entry) async {
+ await videoConductor.getOrCreateController(entry, maxControllerCount: videoPageEntries.length);
+ });
+
+ // auto play/pause when changing page
+ Future<void> _onPageChanged() async {
+ await pauseVideoControllers();
+ if (videoAutoPlayEnabled || (entry.isMotionPhoto && shouldAutoPlayMotionPhoto)) {
+ final page = multiPageController.page;
+ final pageInfo = multiPageInfo.getByIndex(page)!;
+ if (pageInfo.isVideo) {
+ final pageEntry = multiPageInfo.getPageEntryByIndex(page);
+ final pageVideoController = videoConductor.getController(pageEntry);
+ assert(pageVideoController != null);
+ if (pageVideoController != null) {
+ await _autoPlayVideo(pageVideoController, () => entry == entryNotifier.value && page == multiPageController.page);
+ }
+ }
+ }
+ }
+
+ _multiPageControllerPageListeners[multiPageController] = _onPageChanged;
+ multiPageController.pageNotifier.addListener(_onPageChanged);
+ await _onPageChanged();
+
+ if (entry.isMotionPhoto && shouldAutoPlayMotionPhoto) {
+ await Future.delayed(ADurations.motionPhotoAutoPlayDelay);
+ if (entry == entryNotifier.value) {
+ multiPageController.page = 1;
+ }
+ }
+ }
+ }
+
+ Future<void> _cleanMultiPageController(AvesEntry entry) async {
+ final multiPageController = _multiPageControllerPageListeners.keys.firstWhereOrNull((v) => v.entry == entry);
+ if (multiPageController != null) {
+ final _onPageChange = _multiPageControllerPageListeners.remove(multiPageController);
+ if (_onPageChange != null) {
+ multiPageController.pageNotifier.removeListener(_onPageChange);
+ }
+ }
+ }
+
+ Future<void> _autoPlayVideo(AvesVideoController videoController, bool Function() isCurrent, {int? resumeTimeMillis}) async {
+ // video decoding may fail or have initial artifacts when the player initializes
+ // during this widget initialization (because of the page transition and hero animation?)
+ // so we play after a delay for increased stability
+ await Future.delayed(const Duration(milliseconds: 300) * timeDilation);
+
+ if (!videoController.isMuted && (videoController.entry.isAnimated || shouldAutoPlayVideoMuted)) {
+ await videoController.mute(true);
+ }
+
+ if (resumeTimeMillis != null) {
+ await videoController.seekTo(resumeTimeMillis);
+ }
+ await videoController.play();
+
+ // playing controllers are paused when the entry changes,
+ // but the controller may still be preparing (not yet playing) when this happens
+ // so we make sure the current entry is still the same to keep playing
+ if (!isCurrent()) {
+ await videoController.pause();
+ }
+ }
+
+ Future<void> pauseVideoControllers() => context.read<VideoConductor>().pauseAll();
+
+ static const _pipRatioMax = Rational(43, 18);
+ static const _pipRatioMin = Rational(18, 43);
+
+ Future<void> updatePictureInPicture(BuildContext context) async {
+ if (!device.supportPictureInPicture) return;
+
+ if (context.mounted && settings.videoBackgroundMode == VideoBackgroundMode.pip) {
+ final playingController = context.read<VideoConductor>().getPlayingController();
+ if (playingController != null) {
+ final entrySize = playingController.entry.displaySize;
+ final entryAspectRatio = entrySize.aspectRatio;
+ final Rational pipAspectRatio;
+ if (entryAspectRatio > _pipRatioMax.aspectRatio) {
+ pipAspectRatio = _pipRatioMax;
+ } else if (entryAspectRatio < _pipRatioMin.aspectRatio) {
+ pipAspectRatio = _pipRatioMin;
+ } else {
+ pipAspectRatio = Rational(entrySize.width.round(), entrySize.height.round());
+ }
+
+ final viewSize = MediaQuery.sizeOf(context) * MediaQuery.devicePixelRatioOf(context);
+ final fittedSize = applyBoxFit(BoxFit.contain, entrySize, viewSize).destination;
+ final sourceRectHint = Rectangle<int>(
+ ((viewSize.width - fittedSize.width) / 2).round(),
+ ((viewSize.height - fittedSize.height) / 2).round(),
+ fittedSize.width.round(),
+ fittedSize.height.round(),
+ );
+
+ try {
+ final status = await Floating().enable(OnLeavePiP(
+ aspectRatio: pipAspectRatio,
+ sourceRectHint: sourceRectHint,
+ ));
+ debugPrint('Enabled picture-in-picture with status=$status');
+ return;
+ } on PlatformException catch (e, stack) {
+ await reportService.recordError(e, stack);
+ }
+ }
+ }
+
+ debugPrint('Cancelling picture-in-picture');
+ await Floating().cancelOnLeavePiP();
+ }
+}
diff --git a/lib/widgets/viewer/visual/entry_page_view.dart b/lib/widgets/viewer/visual/entry_page_view.dart
new file mode 100644
index 0000000..77f76b6
--- /dev/null
+++ b/lib/widgets/viewer/visual/entry_page_view.dart
@@ -0,0 +1,551 @@
+import 'dart:async';
+
+import 'package:aves/app_mode.dart';
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/props.dart';
+import 'package:aves/model/settings/enums/widget_outline.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/model/viewer/view_state.dart';
+import 'package:aves/services/common/services.dart';
+import 'package:aves/services/media/media_session_service.dart';
+import 'package:aves/theme/icons.dart';
+import 'package:aves/view/view.dart';
+import 'package:aves/widgets/aves_app.dart';
+import 'package:aves/widgets/common/action_mixins/feedback.dart';
+import 'package:aves/widgets/common/basic/insets.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/home_widget.dart';
+import 'package:aves/widgets/viewer/controls/controller.dart';
+import 'package:aves/widgets/viewer/controls/notifications.dart';
+import 'package:aves/widgets/viewer/hero.dart';
+import 'package:aves/widgets/viewer/video/conductor.dart';
+import 'package:aves/widgets/viewer/view/conductor.dart';
+import 'package:aves/widgets/viewer/visual/error.dart';
+import 'package:aves/widgets/viewer/visual/raster.dart';
+import 'package:aves/widgets/viewer/visual/vector.dart';
+import 'package:aves/widgets/viewer/visual/video/cover.dart';
+import 'package:aves/widgets/viewer/visual/video/subtitle/subtitle.dart';
+import 'package:aves/widgets/viewer/visual/video/swipe_action.dart';
+import 'package:aves/widgets/viewer/visual/video/video_view.dart';
+import 'package:aves_magnifier/aves_magnifier.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:decorated_icon/decorated_icon.dart';
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+class EntryPageView extends StatefulWidget {
+ final AvesEntry mainEntry, pageEntry;
+ final ViewerController viewerController;
+ final VoidCallback? onDisposed;
+
+ static const decorationCheckSize = 20.0;
+ static const rasterMaxScale = ScaleLevel(factor: 5);
+ static const vectorMaxScale = ScaleLevel(factor: 25);
+
+ const EntryPageView({
+ super.key,
+ required this.mainEntry,
+ required this.pageEntry,
+ required this.viewerController,
+ this.onDisposed,
+ });
+
+ @override
+ State<EntryPageView> createState() => _EntryPageViewState();
+}
+
+class _EntryPageViewState extends State<EntryPageView> with TickerProviderStateMixin {
+ late ValueNotifier<ViewState> _viewStateNotifier;
+ late AvesMagnifierController _magnifierController;
+ final Set<StreamSubscription> _subscriptions = {};
+ final ValueNotifier<Widget?> _actionFeedbackChildNotifier = ValueNotifier(null);
+ OverlayEntry? _actionFeedbackOverlayEntry;
+
+ AvesEntry get mainEntry => widget.mainEntry;
+
+ AvesEntry get entry => widget.pageEntry;
+
+ ViewerController get viewerController => widget.viewerController;
+
+ @override
+ void initState() {
+ super.initState();
+ _registerWidget(widget);
+ }
+
+ @override
+ void didUpdateWidget(covariant EntryPageView oldWidget) {
+ super.didUpdateWidget(oldWidget);
+
+ if (oldWidget.pageEntry != widget.pageEntry) {
+ _unregisterWidget(oldWidget);
+ _registerWidget(widget);
+ }
+ }
+
+ @override
+ void dispose() {
+ _unregisterWidget(widget);
+ widget.onDisposed?.call();
+ _actionFeedbackChildNotifier.dispose();
+ super.dispose();
+ }
+
+ void _registerWidget(EntryPageView widget) {
+ final entry = widget.pageEntry;
+ _viewStateNotifier = context.read<ViewStateConductor>().getOrCreateController(entry).viewStateNotifier;
+ _magnifierController = AvesMagnifierController();
+ _subscriptions.add(_magnifierController.stateStream.listen(_onViewStateChanged));
+ _subscriptions.add(_magnifierController.scaleBoundariesStream.listen(_onViewScaleBoundariesChanged));
+ if (entry.isVideo) {
+ _subscriptions.add(mediaSessionService.mediaCommands.listen(_onMediaCommand));
+ }
+ viewerController.startAutopilotAnimation(
+ vsync: this,
+ onUpdate: ({required scaleLevel}) {
+ final boundaries = _magnifierController.scaleBoundaries;
+ if (boundaries != null) {
+ final scale = boundaries.scaleForLevel(scaleLevel);
+ _magnifierController.update(scale: scale, source: ChangeSource.animation);
+ }
+ });
+ }
+
+ void _unregisterWidget(EntryPageView oldWidget) {
+ viewerController.stopAutopilotAnimation(vsync: this);
+ _magnifierController.dispose();
+ _subscriptions
+ ..forEach((sub) => sub.cancel())
+ ..clear();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ Widget child = AnimatedBuilder(
+ animation: entry.visualChangeNotifier,
+ builder: (context, child) {
+ Widget? child;
+ if (entry.isSvg) {
+ child = _buildSvgView();
+ } else if (!entry.displaySize.isEmpty) {
+ if (entry.isVideo) {
+ child = _buildVideoView();
+ } else if (entry.isDecodingSupported) {
+ child = _buildRasterView();
+ }
+ }
+
+ child ??= ErrorView(
+ entry: entry,
+ onTap: _onTap,
+ );
+ return child;
+ },
+ );
+
+ if (!settings.viewerUseCutout) {
+ child = SafeCutoutArea(
+ child: ClipRect(
+ child: child,
+ ),
+ );
+ }
+
+ final animate = context.select<Settings, bool>((v) => v.animate);
+ if (animate) {
+ child = Consumer<EntryHeroInfo?>(
+ builder: (context, info, child) => Hero(
+ tag: info != null && info.entry == mainEntry ? info.tag : hashCode,
+ transitionOnUserGestures: true,
+ child: child!,
+ ),
+ child: child,
+ );
+ }
+
+ return child;
+ }
+
+ Widget _buildRasterView() {
+ return _buildMagnifier(
+ applyScale: false,
+ child: RasterImageView(
+ entry: entry,
+ viewStateNotifier: _viewStateNotifier,
+ errorBuilder: (context, error, stackTrace) => ErrorView(
+ entry: entry,
+ onTap: _onTap,
+ ),
+ ),
+ );
+ }
+
+ Widget _buildSvgView() {
+ return _buildMagnifier(
+ maxScale: EntryPageView.vectorMaxScale,
+ scaleStateCycle: _vectorScaleStateCycle,
+ applyScale: false,
+ child: VectorImageView(
+ entry: entry,
+ viewStateNotifier: _viewStateNotifier,
+ errorBuilder: (context, error, stackTrace) => ErrorView(
+ entry: entry,
+ onTap: _onTap,
+ ),
+ ),
+ );
+ }
+
+ Widget _buildVideoView() {
+ final videoController = context.read<VideoConductor>().getController(entry);
+ if (videoController == null) return const SizedBox();
+
+ return ValueListenableBuilder<double?>(
+ valueListenable: videoController.sarNotifier,
+ builder: (context, sar, child) {
+ final videoDisplaySize = entry.videoDisplaySize(sar);
+ final isPureVideo = entry.isPureVideo;
+
+ return Selector<Settings, (bool, bool, bool)>(
+ selector: (context, s) => (
+ isPureVideo && s.videoGestureDoubleTapTogglePlay,
+ isPureVideo && s.videoGestureSideDoubleTapSeek,
+ isPureVideo && s.videoGestureVerticalDragBrightnessVolume,
+ ),
+ builder: (context, s, child) {
+ final (playGesture, seekGesture, useVerticalDragGesture) = s;
+ final useTapGesture = playGesture || seekGesture;
+
+ MagnifierDoubleTapCallback? onDoubleTap;
+ MagnifierGestureScaleStartCallback? onScaleStart;
+ MagnifierGestureScaleUpdateCallback? onScaleUpdate;
+ MagnifierGestureScaleEndCallback? onScaleEnd;
+
+ if (useTapGesture) {
+ void _applyAction(EntryAction action, {IconData? Function()? icon}) {
+ _actionFeedbackChildNotifier.value = DecoratedIcon(
+ icon?.call() ?? action.getIconData(),
+ size: 48,
+ color: Colors.white,
+ shadows: const [
+ Shadow(
+ color: Colors.black,
+ blurRadius: 4,
+ )
+ ],
+ );
+ VideoActionNotification(
+ controller: videoController,
+ entry: entry,
+ action: action,
+ ).dispatch(context);
+ }
+
+ onDoubleTap = (alignment) {
+ final x = alignment.x;
+ if (seekGesture) {
+ final sideRatio = _getSideRatio();
+ if (sideRatio != null) {
+ if (x < sideRatio) {
+ _applyAction(EntryAction.videoReplay10);
+ return true;
+ } else if (x > 1 - sideRatio) {
+ _applyAction(EntryAction.videoSkip10);
+ return true;
+ }
+ }
+ }
+ if (playGesture) {
+ _applyAction(
+ EntryAction.videoTogglePlay,
+ icon: () => videoController.isPlaying ? AIcons.pause : AIcons.play,
+ );
+ return true;
+ }
+ return false;
+ };
+ }
+
+ if (useVerticalDragGesture) {
+ SwipeAction? swipeAction;
+ var move = Offset.zero;
+ var dropped = false;
+ double? startValue;
+ ValueNotifier<double?>? valueNotifier;
+
+ onScaleStart = (details, doubleTap, boundaries) {
+ dropped = details.pointerCount > 1 || doubleTap;
+ if (dropped) return;
+
+ startValue = null;
+ valueNotifier = ValueNotifier<double?>(null);
+ final alignmentX = details.focalPoint.dx / boundaries.viewportSize.width;
+ final action = alignmentX > .5 ? SwipeAction.volume : SwipeAction.brightness;
+ action.get().then((v) => startValue = v);
+ swipeAction = action;
+ move = Offset.zero;
+ _actionFeedbackOverlayEntry = OverlayEntry(
+ builder: (context) => SwipeActionFeedback(
+ action: action,
+ valueNotifier: valueNotifier!,
+ ),
+ );
+ Overlay.of(context).insert(_actionFeedbackOverlayEntry!);
+ };
+ onScaleUpdate = (details) {
+ if (valueNotifier == null) return false;
+
+ move += details.focalPointDelta;
+ dropped |= details.pointerCount > 1;
+ if (valueNotifier!.value == null) {
+ dropped |= MagnifierGestureRecognizer.isXPan(move);
+ }
+ if (dropped) return false;
+
+ final _startValue = startValue;
+ if (_startValue != null) {
+ final double value = (_startValue - move.dy / SwipeActionFeedback.height).clamp(0, 1);
+ valueNotifier!.value = value;
+ swipeAction?.set(value);
+ }
+ return true;
+ };
+ onScaleEnd = (details) {
+ valueNotifier?.dispose();
+
+ _actionFeedbackOverlayEntry
+ ?..remove()
+ ..dispose();
+ _actionFeedbackOverlayEntry = null;
+ };
+ }
+
+ Widget videoChild = Stack(
+ children: [
+ _buildMagnifier(
+ displaySize: videoDisplaySize,
+ onScaleStart: onScaleStart,
+ onScaleUpdate: onScaleUpdate,
+ onScaleEnd: onScaleEnd,
+ onDoubleTap: onDoubleTap,
+ child: VideoView(
+ entry: entry,
+ controller: videoController,
+ ),
+ ),
+ VideoSubtitles(
+ entry: entry,
+ controller: videoController,
+ viewStateNotifier: _viewStateNotifier,
+ ),
+ if (useTapGesture)
+ ValueListenableBuilder<Widget?>(
+ valueListenable: _actionFeedbackChildNotifier,
+ builder: (context, feedbackChild, child) => ActionFeedback(
+ child: feedbackChild,
+ ),
+ ),
+ ],
+ );
+ if (useVerticalDragGesture) {
+ final scope = MagnifierGestureDetectorScope.maybeOf(context);
+ if (scope != null) {
+ videoChild = scope.copyWith(
+ acceptPointerEvent: MagnifierGestureRecognizer.isYPan,
+ child: videoChild,
+ );
+ }
+ }
+ return Stack(
+ fit: StackFit.expand,
+ children: [
+ videoChild,
+ VideoCover(
+ mainEntry: mainEntry,
+ pageEntry: entry,
+ magnifierController: _magnifierController,
+ videoController: videoController,
+ videoDisplaySize: videoDisplaySize,
+ onTap: _onTap,
+ magnifierBuilder: (coverController, coverSize, videoCoverUriImage) => _buildMagnifier(
+ controller: coverController,
+ displaySize: coverSize,
+ onDoubleTap: onDoubleTap,
+ child: Image(
+ image: videoCoverUriImage,
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ },
+ );
+ }
+
+ Widget _buildMagnifier({
+ AvesMagnifierController? controller,
+ Size? displaySize,
+ ScaleLevel maxScale = EntryPageView.rasterMaxScale,
+ ScaleStateCycle scaleStateCycle = defaultScaleStateCycle,
+ bool applyScale = true,
+ MagnifierGestureScaleStartCallback? onScaleStart,
+ MagnifierGestureScaleUpdateCallback? onScaleUpdate,
+ MagnifierGestureScaleEndCallback? onScaleEnd,
+ MagnifierDoubleTapCallback? onDoubleTap,
+ required Widget child,
+ }) {
+ final isWallpaperMode = context.read<ValueNotifier<AppMode>>().value == AppMode.setWallpaper;
+ final minScale = isWallpaperMode ? const ScaleLevel(ref: ScaleReference.covered) : const ScaleLevel(ref: ScaleReference.contained);
+
+ return ValueListenableBuilder<bool>(
+ valueListenable: AvesApp.canGestureToOtherApps,
+ builder: (context, canGestureToOtherApps, child) {
+ return AvesMagnifier(
+ // key includes modified date to refresh when the image is modified by metadata (e.g. rotated)
+ key: Key('${entry.uri}_${entry.pageId}_${entry.dateModifiedMillis}'),
+ controller: controller ?? _magnifierController,
+ contentSize: displaySize ?? entry.displaySize,
+ allowOriginalScaleBeyondRange: !isWallpaperMode,
+ allowDoubleTap: _allowDoubleTap,
+ minScale: minScale,
+ maxScale: maxScale,
+ initialScale: viewerController.initialScale,
+ scaleStateCycle: scaleStateCycle,
+ applyScale: applyScale,
+ onScaleStart: onScaleStart,
+ onScaleUpdate: onScaleUpdate,
+ onScaleEnd: onScaleEnd,
+ onFling: _onFling,
+ onTap: (context, _, alignment, __) {
+ if (context.mounted) {
+ _onTap(alignment: alignment);
+ }
+ },
+ onLongPress: canGestureToOtherApps ? _startGlobalDrag : null,
+ onDoubleTap: onDoubleTap,
+ child: child!,
+ );
+ },
+ child: child,
+ );
+ }
+
+ Future<void> _startGlobalDrag() async {
+ const dragShadowSize = Size.square(128);
+ final cornerRadiusPx = await deviceService.getWidgetCornerRadiusPx();
+
+ final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
+ final brightness = Theme.of(context).brightness;
+ final outline = await WidgetOutline.systemBlackAndWhite.color(brightness);
+
+ final dragShadowBytes = await HomeWidgetPainter(
+ entry: entry,
+ devicePixelRatio: devicePixelRatio,
+ ).drawWidget(
+ sizeDip: dragShadowSize,
+ cornerRadiusPx: cornerRadiusPx,
+ outline: outline,
+ shape: WidgetShape.rrect,
+ );
+
+ await windowService.startGlobalDrag(entry.uri, entry.bestTitle, dragShadowSize, dragShadowBytes);
+ }
+
+ void _onFling(AxisDirection direction) {
+ const animate = true;
+ switch (direction) {
+ case AxisDirection.left:
+ (context.isRtl ? const ShowNextEntryNotification(animate: animate) : const ShowPreviousEntryNotification(animate: animate)).dispatch(context);
+ case AxisDirection.right:
+ (context.isRtl ? const ShowPreviousEntryNotification(animate: animate) : const ShowNextEntryNotification(animate: animate)).dispatch(context);
+ case AxisDirection.up:
+ PopVisualNotification().dispatch(context);
+ case AxisDirection.down:
+ ShowInfoPageNotification().dispatch(context);
+ }
+ }
+
+ Notification? _handleSideSingleTap(Alignment? alignment) {
+ if (settings.viewerGestureSideTapNext && alignment != null) {
+ final x = alignment.x;
+ final sideRatio = _getSideRatio();
+ if (sideRatio != null) {
+ const animate = false;
+ if (x < sideRatio) {
+ return context.isRtl ? const ShowNextEntryNotification(animate: animate) : const ShowPreviousEntryNotification(animate: animate);
+ } else if (x > 1 - sideRatio) {
+ return context.isRtl ? const ShowPreviousEntryNotification(animate: animate) : const ShowNextEntryNotification(animate: animate);
+ }
+ }
+ }
+ return null;
+ }
+
+ void _onTap({Alignment? alignment}) => (_handleSideSingleTap(alignment) ?? const ToggleOverlayNotification()).dispatch(context);
+
+ // side gesture handling by precedence:
+ // - seek in video by side double tap (if enabled)
+ // - go to previous/next entry by side single tap (if enabled)
+ // - zoom in/out by double tap
+ bool _allowDoubleTap(Alignment alignment) {
+ if (entry.isVideo && settings.videoGestureSideDoubleTapSeek) {
+ return true;
+ }
+ final actionNotification = _handleSideSingleTap(alignment);
+ return actionNotification == null;
+ }
+
+ void _onMediaCommand(MediaCommandEvent event) {
+ final videoController = context.read<VideoConductor>().getController(entry);
+ if (videoController == null) return;
+
+ switch (event.command) {
+ case MediaCommand.play:
+ videoController.play();
+ case MediaCommand.pause:
+ videoController.pause();
+ case MediaCommand.skipToNext:
+ ShowNextVideoNotification().dispatch(context);
+ case MediaCommand.skipToPrevious:
+ ShowPreviousVideoNotification().dispatch(context);
+ case MediaCommand.stop:
+ videoController.pause();
+ case MediaCommand.seek:
+ if (event is MediaSeekCommandEvent) {
+ videoController.seekTo(event.position);
+ }
+ }
+ }
+
+ void _onViewStateChanged(MagnifierState v) {
+ if (!mounted) return;
+ _viewStateNotifier.value = _viewStateNotifier.value.copyWith(
+ position: v.position,
+ scale: v.scale,
+ );
+ }
+
+ void _onViewScaleBoundariesChanged(ScaleBoundaries v) {
+ _viewStateNotifier.value = _viewStateNotifier.value.copyWith(
+ viewportSize: v.viewportSize,
+ contentSize: v.contentSize,
+ );
+ }
+
+ double? _getSideRatio() {
+ if (!mounted) return null;
+ final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait;
+ return isPortrait ? 1 / 6 : 1 / 8;
+ }
+
+ static ScaleState _vectorScaleStateCycle(ScaleState actual) {
+ switch (actual) {
+ case ScaleState.initial:
+ return ScaleState.covering;
+ default:
+ return ScaleState.initial;
+ }
+ }
+}
diff --git a/lib/widgets/viewer/visual/error.dart b/lib/widgets/viewer/visual/error.dart
new file mode 100644
index 0000000..5354d56
--- /dev/null
+++ b/lib/widgets/viewer/visual/error.dart
@@ -0,0 +1,60 @@
+import 'dart:io';
+
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/theme/icons.dart';
+import 'package:aves/widgets/common/extensions/build_context.dart';
+import 'package:aves/widgets/common/identity/empty.dart';
+import 'package:aves/widgets/viewer/entry_viewer_page.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+
+class ErrorView extends StatefulWidget {
+ final AvesEntry entry;
+ final VoidCallback onTap;
+
+ const ErrorView({
+ super.key,
+ required this.entry,
+ required this.onTap,
+ });
+
+ @override
+ State<ErrorView> createState() => _ErrorViewState();
+}
+
+class _ErrorViewState extends State<ErrorView> {
+ late Future<bool> _exists;
+
+ AvesEntry get entry => widget.entry;
+
+ @override
+ void initState() {
+ super.initState();
+ final path = entry.trashDetails?.path ?? entry.path;
+ _exists = path != null ? File(path).exists() : SynchronousFuture(true);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return GestureDetector(
+ onTap: () => widget.onTap(),
+ // use container to expand constraints, so that the user can tap anywhere
+ child: Container(
+ // opaque to cover potential lower quality layer below
+ color: EntryViewerPage.getBackground(context),
+ child: FutureBuilder<bool>(
+ future: _exists,
+ builder: (context, snapshot) {
+ if (snapshot.connectionState != ConnectionState.done) return const SizedBox();
+ final exists = snapshot.data!;
+ return EmptyContent(
+ icon: exists ? AIcons.error : AIcons.broken,
+ text: exists ? context.l10n.viewerErrorUnknown : context.l10n.viewerErrorDoesNotExist,
+ alignment: Alignment.center,
+ safeBottom: false,
+ );
+ }),
+ ),
+ );
+ }
+}
diff --git a/lib/widgets/viewer/visual/raster.dart b/lib/widgets/viewer/visual/raster.dart
new file mode 100644
index 0000000..9b77b3c
--- /dev/null
+++ b/lib/widgets/viewer/visual/raster.dart
@@ -0,0 +1,517 @@
+import 'dart:math';
+
+import 'package:aves/image_providers/region_provider.dart';
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/images.dart';
+import 'package:aves/model/entry/extensions/props.dart';
+import 'package:aves/model/settings/enums/entry_background.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/model/viewer/view_state.dart';
+import 'package:aves/widgets/common/fx/checkered_decoration.dart';
+import 'package:aves/widgets/viewer/controls/notifications.dart';
+import 'package:aves/widgets/viewer/visual/entry_page_view.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:latlong2/latlong.dart';
+
+class RasterImageView extends StatefulWidget {
+ final AvesEntry entry;
+ final ValueNotifier<ViewState> viewStateNotifier;
+ final ImageErrorWidgetBuilder errorBuilder;
+
+ const RasterImageView({
+ super.key,
+ required this.entry,
+ required this.viewStateNotifier,
+ required this.errorBuilder,
+ });
+
+ @override
+ State<RasterImageView> createState() => _RasterImageViewState();
+}
+
+class _RasterImageViewState extends State<RasterImageView> {
+ late Size _displaySize;
+ late bool _useTiles;
+ bool _isTilingInitialized = false;
+ late int _maxSampleSize;
+ late double _tileSide;
+ Matrix4? _tileTransform;
+ ImageStream? _fullImageStream;
+ late ImageStreamListener _fullImageListener;
+ final ValueNotifier<bool> _fullImageLoaded = ValueNotifier(false);
+ ImageInfo? _fullImageInfo;
+
+ static const int _pixelArtMaxSize = 256; // px
+ static const double _tilesByShortestSide = 2;
+
+ AvesEntry get entry => widget.entry;
+
+ ValueNotifier<ViewState> get viewStateNotifier => widget.viewStateNotifier;
+
+ ViewState get viewState => viewStateNotifier.value;
+
+ ImageProvider get thumbnailProvider => entry.bestCachedThumbnail;
+
+ ImageProvider get fullImageProvider {
+ if (_useTiles) {
+ assert(_isTilingInitialized);
+ return entry.getRegion(
+ sampleSize: _maxSampleSize,
+ region: entry.fullImageRegion,
+ );
+ } else {
+ return entry.fullImage;
+ }
+ }
+
+ @override
+ void initState() {
+ super.initState();
+ _displaySize = entry.displaySize;
+ _useTiles = entry.useTiles;
+ _fullImageListener = ImageStreamListener(_onFullImageCompleted);
+ if (!_useTiles) _registerFullImage();
+ }
+
+ @override
+ void didUpdateWidget(covariant RasterImageView oldWidget) {
+ super.didUpdateWidget(oldWidget);
+
+ final oldViewState = oldWidget.viewStateNotifier.value;
+ final viewState = widget.viewStateNotifier.value;
+ if (oldWidget.entry != widget.entry || oldViewState.viewportSize != viewState.viewportSize) {
+ _isTilingInitialized = false;
+ _fullImageLoaded.value = false;
+ _unregisterFullImage();
+ }
+ }
+
+ @override
+ void dispose() {
+ _fullImageLoaded.dispose();
+ _unregisterFullImage();
+ super.dispose();
+ }
+
+ void _registerFullImage() {
+ _fullImageStream = fullImageProvider.resolve(ImageConfiguration.empty);
+ _fullImageStream!.addListener(_fullImageListener);
+ }
+
+ void _unregisterFullImage() {
+ _fullImageStream?.removeListener(_fullImageListener);
+ _fullImageStream = null;
+ _fullImageInfo?.dispose();
+ }
+
+ void _onFullImageCompleted(ImageInfo image, bool synchronousCall) {
+ // implementer is responsible for disposing the provided `ImageInfo`
+ _unregisterFullImage();
+ _fullImageInfo = image;
+ _fullImageLoaded.value = true;
+ FullImageLoadedNotification(entry, fullImageProvider).dispatch(context);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return ValueListenableBuilder<ViewState>(
+ valueListenable: viewStateNotifier,
+ builder: (context, viewState, child) {
+ final viewportSize = viewState.viewportSize;
+ final viewportSized = viewportSize?.isEmpty == false;
+ if (viewportSized && _useTiles && !_isTilingInitialized) _initTiling(viewportSize!);
+
+ final magnifierScale = viewState.scale!;
+ return SizedBox.fromSize(
+ size: _displaySize * magnifierScale,
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ if (entry.canHaveAlpha && viewportSized) _buildBackground(),
+ _buildLoading(),
+ if (_useTiles) ..._buildTiles() else _buildFullImage(),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildFullImage() {
+ final magnifierScale = viewState.scale!;
+ final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
+ final quality = _qualityForScaleAndSize(
+ magnifierScale: magnifierScale,
+ sampleSize: 1,
+ devicePixelRatio: devicePixelRatio,
+ );
+ return Image(
+ image: fullImageProvider,
+ gaplessPlayback: true,
+ errorBuilder: widget.errorBuilder,
+ width: (_displaySize * magnifierScale).width,
+ fit: BoxFit.contain,
+ filterQuality: quality,
+ );
+ }
+
+ void _initTiling(Size viewportSize) {
+ final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
+ _tileSide = viewportSize.shortestSide * devicePixelRatio / _tilesByShortestSide;
+ // scale for initial state `contained`
+ final containedScale = min(viewportSize.width / _displaySize.width, viewportSize.height / _displaySize.height);
+ _maxSampleSize = ExtraAvesEntryImages.sampleSizeForScale(magnifierScale: containedScale, devicePixelRatio: devicePixelRatio);
+
+ final rotationDegrees = entry.rotationDegrees;
+ final isFlipped = entry.isFlipped;
+ _tileTransform = null;
+ if (rotationDegrees != 0 || isFlipped) {
+ _tileTransform = Matrix4.identity()
+ ..translate(entry.width / 2.0, entry.height / 2.0)
+ ..scale(isFlipped ? -1.0 : 1.0, 1.0, 1.0)
+ ..rotateZ(-degToRadian(rotationDegrees.toDouble()))
+ ..translate(-_displaySize.width / 2.0, -_displaySize.height / 2.0);
+ }
+ _isTilingInitialized = true;
+ _registerFullImage();
+ }
+
+ Widget _buildLoading() {
+ return ValueListenableBuilder<bool>(
+ valueListenable: _fullImageLoaded,
+ builder: (context, fullImageLoaded, child) {
+ if (fullImageLoaded) return const SizedBox();
+
+ return Center(
+ child: AspectRatio(
+ // enforce original aspect ratio, as some thumbnails aspect ratios slightly differ
+ aspectRatio: entry.displayAspectRatio,
+ child: Image(
+ image: thumbnailProvider,
+ fit: BoxFit.fill,
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _buildBackground() {
+ final viewportSize = viewState.viewportSize!;
+ final viewSize = _displaySize * viewState.scale!;
+ final decorationOffset = ((viewSize - viewportSize) as Offset) / 2 - viewState.position;
+ // deflate as a quick way to prevent background bleed
+ final decorationSize = (applyBoxFit(BoxFit.none, viewSize, viewportSize).source - const Offset(.5, .5)) as Size;
+
+ Widget child;
+ final background = settings.imageBackground;
+ if (background == EntryBackground.checkered) {
+ final side = viewportSize.shortestSide;
+ final checkSize = side / ((side / EntryPageView.decorationCheckSize).round());
+ final offset = ((decorationSize - viewportSize) as Offset) / 2;
+ child = ValueListenableBuilder<bool>(
+ valueListenable: _fullImageLoaded,
+ builder: (context, fullImageLoaded, child) {
+ if (!fullImageLoaded) return const SizedBox();
+
+ return CustomPaint(
+ painter: CheckeredPainter(
+ checkSize: checkSize,
+ offset: offset,
+ ),
+ );
+ },
+ );
+ } else {
+ child = DecoratedBox(
+ decoration: BoxDecoration(
+ color: background.color,
+ ),
+ );
+ }
+ return Positioned(
+ left: decorationOffset.dx >= 0 ? decorationOffset.dx : null,
+ top: decorationOffset.dy >= 0 ? decorationOffset.dy : null,
+ width: decorationSize.width,
+ height: decorationSize.height,
+ child: child,
+ );
+ }
+
+ List<Widget> _buildTiles() {
+ if (!_isTilingInitialized) return [];
+
+ final displayWidth = _displaySize.width.round();
+ final displayHeight = _displaySize.height.round();
+ final viewRect = _getViewRect(displayWidth, displayHeight);
+ final magnifierScale = viewState.scale!;
+ final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
+
+ // for the largest sample size (matching the initial scale), the whole image is in view
+ // so we subsample the whole image without tiling
+ final fullImageRegionTile = _RegionTile(
+ entry: entry,
+ tileRect: Rect.fromLTWH(0, 0, displayWidth * magnifierScale, displayHeight * magnifierScale),
+ regionRect: entry.fullImageRegion,
+ sampleSize: _maxSampleSize,
+ quality: _qualityForScaleAndSize(
+ magnifierScale: magnifierScale,
+ sampleSize: _maxSampleSize,
+ devicePixelRatio: devicePixelRatio,
+ ),
+ );
+ final tiles = [fullImageRegionTile];
+
+ final minSampleSize = min(ExtraAvesEntryImages.sampleSizeForScale(magnifierScale: magnifierScale, devicePixelRatio: devicePixelRatio), _maxSampleSize);
+ int nextSampleSize(int sampleSize) => (sampleSize / 2).floor();
+ for (var sampleSize = nextSampleSize(_maxSampleSize); sampleSize >= minSampleSize; sampleSize = nextSampleSize(sampleSize)) {
+ final regionSide = (_tileSide * sampleSize).round();
+ for (var x = 0; x < displayWidth; x += regionSide) {
+ for (var y = 0; y < displayHeight; y += regionSide) {
+ final rects = _getTileRects(
+ x: x,
+ y: y,
+ regionSide: regionSide,
+ displayWidth: displayWidth,
+ displayHeight: displayHeight,
+ scale: magnifierScale,
+ viewRect: viewRect,
+ );
+ if (rects != null) {
+ final (tileRect, regionRect) = rects;
+ tiles.add(_RegionTile(
+ entry: entry,
+ tileRect: tileRect,
+ regionRect: regionRect,
+ sampleSize: sampleSize,
+ quality: _qualityForScaleAndSize(
+ magnifierScale: magnifierScale,
+ sampleSize: sampleSize,
+ devicePixelRatio: devicePixelRatio,
+ ),
+ ));
+ }
+ }
+ }
+ }
+ return tiles;
+ }
+
+ Rect _getViewRect(int displayWidth, int displayHeight) {
+ final scale = viewState.scale!;
+ final centerOffset = viewState.position;
+ final viewportSize = viewState.viewportSize!;
+ final viewOrigin = Offset(
+ ((displayWidth * scale - viewportSize.width) / 2 - centerOffset.dx),
+ ((displayHeight * scale - viewportSize.height) / 2 - centerOffset.dy),
+ );
+ return viewOrigin & viewportSize;
+ }
+
+ (Rect tileRect, Rectangle<num> regionRect)? _getTileRects({
+ required int x,
+ required int y,
+ required int regionSide,
+ required int displayWidth,
+ required int displayHeight,
+ required double scale,
+ required Rect viewRect,
+ }) {
+ final nextX = x + regionSide;
+ final nextY = y + regionSide;
+ final thisRegionWidth = regionSide - (nextX >= displayWidth ? nextX - displayWidth : 0);
+ final thisRegionHeight = regionSide - (nextY >= displayHeight ? nextY - displayHeight : 0);
+ final tileRect = Rect.fromLTWH(x * scale, y * scale, thisRegionWidth * scale, thisRegionHeight * scale);
+
+ // only build visible tiles
+ if (!viewRect.overlaps(tileRect)) return null;
+
+ Rectangle<num> regionRect;
+ if (_tileTransform != null) {
+ // apply EXIF orientation
+ final regionRectDouble = Rect.fromLTWH(x.toDouble(), y.toDouble(), thisRegionWidth.toDouble(), thisRegionHeight.toDouble());
+ final tl = MatrixUtils.transformPoint(_tileTransform!, regionRectDouble.topLeft);
+ final br = MatrixUtils.transformPoint(_tileTransform!, regionRectDouble.bottomRight);
+ regionRect = Rectangle<double>.fromPoints(
+ Point<double>(tl.dx, tl.dy),
+ Point<double>(br.dx, br.dy),
+ );
+ } else {
+ regionRect = Rectangle<num>(x, y, thisRegionWidth, thisRegionHeight);
+ }
+ return (tileRect, regionRect);
+ }
+
+ // follow recommended thresholds from `FilterQuality` documentation
+ static FilterQuality _qualityForScale({
+ required double magnifierScale,
+ required int sampleSize,
+ required double devicePixelRatio,
+ }) {
+ final entryScale = magnifierScale * devicePixelRatio;
+ final renderingScale = entryScale * sampleSize;
+ if (renderingScale > 1) {
+ return renderingScale > 10 ? FilterQuality.high : FilterQuality.medium;
+ } else {
+ return renderingScale < .5 ? FilterQuality.medium : FilterQuality.high;
+ }
+ }
+
+ // usually follow recommendations, except for small images
+ // (like icons, pixel art, etc.) for which the "nearest neighbor" algorithm is used
+ FilterQuality _qualityForScaleAndSize({
+ required double magnifierScale,
+ required int sampleSize,
+ required double devicePixelRatio,
+ }) {
+ if (_displaySize.longestSide < _pixelArtMaxSize) {
+ return FilterQuality.none;
+ }
+
+ return _qualityForScale(
+ magnifierScale: magnifierScale,
+ sampleSize: sampleSize,
+ devicePixelRatio: devicePixelRatio,
+ );
+ }
+}
+
+class _RegionTile extends StatefulWidget {
+ final AvesEntry entry;
+
+ // `tileRect` uses Flutter view coordinates
+ // `regionRect` uses the raw image pixel coordinates
+ final Rect tileRect;
+ final Rectangle<num> regionRect;
+ final int sampleSize;
+ final FilterQuality quality;
+
+ const _RegionTile({
+ required this.entry,
+ required this.tileRect,
+ required this.regionRect,
+ required this.sampleSize,
+ required this.quality,
+ });
+
+ @override
+ State<_RegionTile> createState() => _RegionTileState();
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(IntProperty('id', entry.id));
+ properties.add(IntProperty('contentId', entry.contentId));
+ properties.add(DiagnosticsProperty<Rect>('tileRect', tileRect));
+ properties.add(DiagnosticsProperty<Rectangle<num>>('regionRect', regionRect));
+ properties.add(IntProperty('sampleSize', sampleSize));
+ }
+}
+
+class _RegionTileState extends State<_RegionTile> {
+ late RegionProvider _provider;
+
+ AvesEntry get entry => widget.entry;
+
+ @override
+ void initState() {
+ super.initState();
+ _registerWidget(widget);
+ }
+
+ @override
+ void didUpdateWidget(covariant _RegionTile oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.entry != widget.entry || oldWidget.tileRect != widget.tileRect || oldWidget.sampleSize != widget.sampleSize || oldWidget.sampleSize != widget.sampleSize) {
+ _unregisterWidget(oldWidget);
+ _registerWidget(widget);
+ }
+ }
+
+ @override
+ void dispose() {
+ _unregisterWidget(widget);
+ super.dispose();
+ }
+
+ void _registerWidget(_RegionTile widget) {
+ _initProvider();
+ }
+
+ void _unregisterWidget(_RegionTile widget) {
+ _pauseProvider();
+ }
+
+ void _initProvider() {
+ _provider = entry.getRegion(
+ sampleSize: widget.sampleSize,
+ region: widget.regionRect,
+ );
+ }
+
+ void _pauseProvider() => _provider.pause();
+
+ @override
+ Widget build(BuildContext context) {
+ final tileRect = widget.tileRect;
+
+ Widget child = Image(
+ image: _provider,
+ width: tileRect.width,
+ height: tileRect.height,
+ fit: BoxFit.fill,
+ filterQuality: widget.quality,
+ );
+
+ // apply EXIF orientation
+ final quarterTurns = entry.rotationDegrees ~/ 90;
+ if (entry.isFlipped) {
+ final rotated = quarterTurns % 2 != 0;
+ final w = (rotated ? tileRect.height : tileRect.width) / 2.0;
+ final h = (rotated ? tileRect.width : tileRect.height) / 2.0;
+ final flipper = Matrix4.identity()
+ ..translate(w, h)
+ ..scale(-1.0, 1.0, 1.0)
+ ..translate(-w, -h);
+ child = Transform(
+ transform: flipper,
+ child: child,
+ );
+ }
+ if (quarterTurns != 0) {
+ child = RotatedBox(
+ quarterTurns: quarterTurns,
+ child: child,
+ );
+ }
+
+ if (settings.debugShowViewerTiles) {
+ final regionRect = widget.regionRect;
+ child = Stack(
+ children: [
+ Positioned.fill(child: child),
+ Text(
+ '\ntile=(${tileRect.left.round()}, ${tileRect.top.round()}) ${tileRect.width.round()} x ${tileRect.height.round()}'
+ '\nregion=(${regionRect.left.round()}, ${regionRect.top.round()}) ${regionRect.width.round()} x ${regionRect.height.round()}'
+ '\nsampling=${widget.sampleSize} quality=${widget.quality.name}',
+ style: const TextStyle(backgroundColor: Colors.black87),
+ ),
+ Positioned.fill(
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ border: Border.all(color: Colors.red, width: 1),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ return Positioned.fromRect(
+ rect: tileRect,
+ child: child,
+ );
+ }
+}
diff --git a/lib/widgets/viewer/visual/vector.dart b/lib/widgets/viewer/visual/vector.dart
new file mode 100644
index 0000000..207d6bc
--- /dev/null
+++ b/lib/widgets/viewer/visual/vector.dart
@@ -0,0 +1,443 @@
+import 'dart:math';
+
+import 'package:aves/image_providers/region_provider.dart';
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/images.dart';
+import 'package:aves/model/settings/enums/entry_background.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/model/viewer/view_state.dart';
+import 'package:aves/utils/math_utils.dart';
+import 'package:aves/widgets/common/fx/checkered_decoration.dart';
+import 'package:aves/widgets/viewer/visual/entry_page_view.dart';
+import 'package:aves_model/aves_model.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+
+class VectorImageView extends StatefulWidget {
+ final AvesEntry entry;
+ final ValueNotifier<ViewState> viewStateNotifier;
+ final ImageErrorWidgetBuilder errorBuilder;
+
+ const VectorImageView({
+ super.key,
+ required this.entry,
+ required this.viewStateNotifier,
+ required this.errorBuilder,
+ });
+
+ @override
+ State<VectorImageView> createState() => _VectorImageViewState();
+}
+
+class _VectorImageViewState extends State<VectorImageView> {
+ late Size _displaySize;
+ bool _isTilingInitialized = false;
+ late double _minScale;
+ late double _tileSide;
+ ImageStream? _fullImageStream;
+ late ImageStreamListener _fullImageListener;
+ final ValueNotifier<bool> _fullImageLoaded = ValueNotifier(false);
+ ImageInfo? _fullImageInfo;
+
+ AvesEntry get entry => widget.entry;
+
+ ValueNotifier<ViewState> get viewStateNotifier => widget.viewStateNotifier;
+
+ ViewState get viewState => viewStateNotifier.value;
+
+ ImageProvider get thumbnailProvider => entry.bestCachedThumbnail;
+
+ ImageProvider get fullImageProvider {
+ assert(_isTilingInitialized);
+ return entry.getRegion(
+ scale: _minScale,
+ region: entry.fullImageRegion,
+ );
+ }
+
+ @override
+ void initState() {
+ super.initState();
+ _displaySize = entry.displaySize;
+ _fullImageListener = ImageStreamListener(_onFullImageCompleted);
+ }
+
+ @override
+ void didUpdateWidget(covariant VectorImageView oldWidget) {
+ super.didUpdateWidget(oldWidget);
+
+ final oldViewState = oldWidget.viewStateNotifier.value;
+ final viewState = widget.viewStateNotifier.value;
+ if (oldWidget.entry != widget.entry || oldViewState.viewportSize != viewState.viewportSize) {
+ _isTilingInitialized = false;
+ _fullImageLoaded.value = false;
+ _unregisterFullImage();
+ }
+ }
+
+ @override
+ void dispose() {
+ _fullImageLoaded.dispose();
+ _unregisterFullImage();
+ super.dispose();
+ }
+
+ void _registerFullImage() {
+ _fullImageStream = fullImageProvider.resolve(ImageConfiguration.empty);
+ _fullImageStream!.addListener(_fullImageListener);
+ }
+
+ void _unregisterFullImage() {
+ _fullImageStream?.removeListener(_fullImageListener);
+ _fullImageStream = null;
+ _fullImageInfo?.dispose();
+ }
+
+ void _onFullImageCompleted(ImageInfo image, bool synchronousCall) {
+ // implementer is responsible for disposing the provided `ImageInfo`
+ _unregisterFullImage();
+ _fullImageInfo = image;
+ _fullImageLoaded.value = true;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (_displaySize == Size.zero) return widget.errorBuilder(context, 'Not sized', null);
+
+ final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
+ return ValueListenableBuilder<ViewState>(
+ valueListenable: viewStateNotifier,
+ builder: (context, viewState, child) {
+ final viewportSize = viewState.viewportSize;
+ final viewportSized = viewportSize?.isEmpty == false;
+ if (viewportSized && !_isTilingInitialized) {
+ _initTiling(
+ viewportSize: viewportSize!,
+ devicePixelRatio: devicePixelRatio,
+ );
+ }
+
+ return SizedBox.fromSize(
+ size: _displaySize * viewState.scale!,
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ _buildLoading(),
+ ..._getTiles(devicePixelRatio),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ void _initTiling({
+ required Size viewportSize,
+ required double devicePixelRatio,
+ }) {
+ _tileSide = _displaySize.longestSide;
+ // scale for initial state `contained`
+ final containedScale = min(viewportSize.width / _displaySize.width, viewportSize.height / _displaySize.height);
+ _minScale = _imageScaleForViewScale(scale: containedScale, devicePixelRatio: devicePixelRatio);
+
+ _isTilingInitialized = true;
+ _registerFullImage();
+ }
+
+ Widget _buildLoading() {
+ return ValueListenableBuilder<bool>(
+ valueListenable: _fullImageLoaded,
+ builder: (context, fullImageLoaded, child) {
+ if (fullImageLoaded) return const SizedBox();
+
+ return Center(
+ child: AspectRatio(
+ // enforce original aspect ratio, as some thumbnails aspect ratios slightly differ
+ aspectRatio: entry.displayAspectRatio,
+ child: Image(
+ image: thumbnailProvider,
+ fit: BoxFit.fill,
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ List<Widget> _getTiles(double devicePixelRatio) {
+ if (!_isTilingInitialized) return [];
+
+ final displayWidth = _displaySize.width;
+ final displayHeight = _displaySize.height;
+ final viewRect = _getViewRect(displayWidth, displayHeight);
+ final viewScale = viewState.scale!;
+ final background = settings.imageBackground;
+
+ Color? backgroundColor;
+ _BackgroundFrameBuilder? backgroundFrameBuilder;
+ if (background.isColor) {
+ backgroundColor = background.color;
+ } else if (background == EntryBackground.checkered) {
+ final viewportSize = viewState.viewportSize!;
+ final viewSize = _displaySize * viewState.scale!;
+
+ final backgroundSize = applyBoxFit(BoxFit.none, viewSize, viewportSize).source;
+ var backgroundOffset = ((viewSize - viewportSize) as Offset) / 2 - viewState.position;
+ backgroundOffset = Offset(max(0, backgroundOffset.dx), max(0, backgroundOffset.dy));
+ backgroundOffset += ((backgroundSize - viewportSize) as Offset) / 2;
+
+ final side = viewportSize.shortestSide;
+ final checkSize = side / ((side / EntryPageView.decorationCheckSize).round());
+
+ backgroundFrameBuilder = (child, frame, tileRect) {
+ return frame == null
+ ? const SizedBox()
+ : DecoratedBox(
+ decoration: _CheckeredBackgroundDecoration(
+ viewportSize: viewportSize,
+ checkSize: checkSize,
+ offset: backgroundOffset - tileRect.topLeft,
+ ),
+ child: child,
+ );
+ };
+ }
+
+ // for the largest sample size (matching the initial scale), the whole image is in view
+ // so we subsample the whole image without tiling
+ final fullImageRegionTile = _RegionTile(
+ entry: entry,
+ tileRect: Rect.fromLTWH(0, 0, displayWidth * viewScale, displayHeight * viewScale),
+ regionRect: entry.fullImageRegion,
+ scale: _minScale,
+ backgroundColor: backgroundColor,
+ backgroundFrameBuilder: backgroundFrameBuilder,
+ );
+ final tiles = <Widget>[fullImageRegionTile];
+
+ final maxSvgScale = max(_imageScaleForViewScale(scale: viewScale, devicePixelRatio: devicePixelRatio), _minScale);
+ double nextScale(double scale) => scale * 2;
+ // add `alpha` to the region side so that tiles do not align across layers,
+ // which helps the checkered background deflation workaround
+ // for the tile background bleeding issue
+ var alpha = 0;
+ for (var svgScale = nextScale(_minScale); svgScale <= maxSvgScale; svgScale = nextScale(svgScale)) {
+ final regionSide = (_tileSide + alpha++) / (svgScale / _minScale);
+ for (var x = .0; x < displayWidth; x += regionSide) {
+ for (var y = .0; y < displayHeight; y += regionSide) {
+ final rects = _getTileRects(
+ x: x,
+ y: y,
+ regionSide: regionSide,
+ displayWidth: displayWidth,
+ displayHeight: displayHeight,
+ scale: viewScale,
+ viewRect: viewRect,
+ );
+ if (rects != null) {
+ final (tileRect, regionRect) = rects;
+ tiles.add(_RegionTile(
+ entry: entry,
+ tileRect: tileRect,
+ regionRect: regionRect,
+ scale: svgScale,
+ backgroundColor: backgroundColor,
+ backgroundFrameBuilder: backgroundFrameBuilder,
+ ));
+ }
+ }
+ }
+ }
+ return tiles;
+ }
+
+ Rect _getViewRect(double displayWidth, double displayHeight) {
+ final scale = viewState.scale!;
+ final centerOffset = viewState.position;
+ final viewportSize = viewState.viewportSize!;
+ final viewOrigin = Offset(
+ ((displayWidth * scale - viewportSize.width) / 2 - centerOffset.dx),
+ ((displayHeight * scale - viewportSize.height) / 2 - centerOffset.dy),
+ );
+ return viewOrigin & viewportSize;
+ }
+
+ (Rect tileRect, Rectangle<double> regionRect)? _getTileRects({
+ required double x,
+ required double y,
+ required double regionSide,
+ required double displayWidth,
+ required double displayHeight,
+ required double scale,
+ required Rect viewRect,
+ }) {
+ final nextX = x + regionSide;
+ final nextY = y + regionSide;
+ final thisRegionWidth = regionSide - (nextX >= displayWidth ? nextX - displayWidth : 0);
+ final thisRegionHeight = regionSide - (nextY >= displayHeight ? nextY - displayHeight : 0);
+ final tileRect = Rect.fromLTWH(x * scale, y * scale, thisRegionWidth * scale, thisRegionHeight * scale);
+
+ // only build visible tiles
+ if (!viewRect.overlaps(tileRect)) return null;
+
+ final regionRect = Rectangle<double>(x, y, thisRegionWidth, thisRegionHeight);
+ return (tileRect, regionRect);
+ }
+
+ double _imageScaleForViewScale({
+ required double scale,
+ required double devicePixelRatio,
+ }) =>
+ smallestPowerOf2(scale * devicePixelRatio, allowNegativePower: true).toDouble();
+}
+
+typedef _BackgroundFrameBuilder = Widget Function(Widget child, int? frame, Rect tileRect);
+
+class _RegionTile extends StatefulWidget {
+ final AvesEntry entry;
+
+ // `tileRect` uses Flutter view coordinates
+ // `regionRect` uses the raw image pixel coordinates
+ final Rect tileRect;
+ final Rectangle<double> regionRect;
+ final double scale;
+ final Color? backgroundColor;
+ final _BackgroundFrameBuilder? backgroundFrameBuilder;
+
+ const _RegionTile({
+ required this.entry,
+ required this.tileRect,
+ required this.regionRect,
+ required this.scale,
+ required this.backgroundColor,
+ required this.backgroundFrameBuilder,
+ });
+
+ @override
+ State<_RegionTile> createState() => _RegionTileState();
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(IntProperty('id', entry.id));
+ properties.add(IntProperty('contentId', entry.contentId));
+ properties.add(DiagnosticsProperty<Rect>('tileRect', tileRect));
+ properties.add(DiagnosticsProperty<Rectangle<double>>('regionRect', regionRect));
+ properties.add(DoubleProperty('scale', scale));
+ }
+}
+
+class _RegionTileState extends State<_RegionTile> {
+ late RegionProvider _provider;
+
+ AvesEntry get entry => widget.entry;
+
+ @override
+ void initState() {
+ super.initState();
+ _registerWidget(widget);
+ }
+
+ @override
+ void didUpdateWidget(covariant _RegionTile oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.entry != widget.entry || oldWidget.tileRect != widget.tileRect || oldWidget.scale != widget.scale || oldWidget.scale != widget.scale) {
+ _unregisterWidget(oldWidget);
+ _registerWidget(widget);
+ }
+ }
+
+ @override
+ void dispose() {
+ _unregisterWidget(widget);
+ super.dispose();
+ }
+
+ void _registerWidget(_RegionTile widget) {
+ _initProvider();
+ }
+
+ void _unregisterWidget(_RegionTile widget) {
+ _pauseProvider();
+ }
+
+ void _initProvider() {
+ _provider = entry.getRegion(
+ scale: widget.scale,
+ region: widget.regionRect,
+ );
+ }
+
+ void _pauseProvider() => _provider.pause();
+
+ @override
+ Widget build(BuildContext context) {
+ final tileRect = widget.tileRect;
+
+ Widget child = Image(
+ image: _provider,
+ frameBuilder: (_, child, frame, __) => widget.backgroundFrameBuilder?.call(child, frame, tileRect) ?? child,
+ width: tileRect.width,
+ height: tileRect.height,
+ color: widget.backgroundColor,
+ colorBlendMode: BlendMode.dstOver,
+ fit: BoxFit.fill,
+ );
+
+ return Positioned.fromRect(
+ rect: tileRect,
+ child: child,
+ );
+ }
+}
+
+class _CheckeredBackgroundDecoration extends Decoration {
+ final Size viewportSize;
+ final double checkSize;
+ final Offset offset;
+
+ const _CheckeredBackgroundDecoration({
+ required this.viewportSize,
+ required this.checkSize,
+ required this.offset,
+ });
+
+ @override
+ _CheckeredBackgroundDecorationPainter createBoxPainter([VoidCallback? onChanged]) {
+ return _CheckeredBackgroundDecorationPainter(this, onChanged);
+ }
+}
+
+class _CheckeredBackgroundDecorationPainter extends BoxPainter {
+ final _CheckeredBackgroundDecoration decoration;
+
+ const _CheckeredBackgroundDecorationPainter(this.decoration, VoidCallback? onChanged) : super(onChanged);
+
+ static const deflation = Offset(.5, .5);
+
+ @override
+ void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
+ final size = configuration.size;
+ if (size == null) return;
+
+ var decorated = offset & size;
+ // deflate background as a workaround for background bleeding beyond tile image
+ decorated = Rect.fromLTRB(
+ decorated.left + deflation.dx,
+ decorated.top + deflation.dy,
+ decorated.right - deflation.dx,
+ decorated.bottom - deflation.dy,
+ );
+
+ final visible = decorated.intersect(Offset.zero & decoration.viewportSize);
+ final checkOffset = decoration.offset + decorated.topLeft - visible.topLeft - deflation;
+
+ final translation = Offset(max(0, offset.dx + deflation.dx), max(0, offset.dy + deflation.dy));
+ canvas.translate(translation.dx, translation.dy);
+ CheckeredPainter(
+ checkSize: decoration.checkSize,
+ offset: checkOffset,
+ ).paint(canvas, visible.size);
+ canvas.translate(-translation.dx, -translation.dy);
+ }
+}
diff --git a/lib/widgets/viewer/visual/video/cover.dart b/lib/widgets/viewer/visual/video/cover.dart
new file mode 100644
index 0000000..e7df3d5
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/cover.dart
@@ -0,0 +1,164 @@
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/images.dart';
+import 'package:aves/model/entry/extensions/multipage.dart';
+import 'package:aves/theme/durations.dart';
+import 'package:aves/widgets/common/thumbnail/image.dart';
+import 'package:aves_magnifier/aves_magnifier.dart';
+import 'package:aves_video/aves_video.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+
+class VideoCover extends StatefulWidget {
+ final AvesEntry mainEntry, pageEntry;
+ final AvesMagnifierController magnifierController;
+ final AvesVideoController videoController;
+ final Size videoDisplaySize;
+ final void Function({Alignment? alignment}) onTap;
+ final Widget Function(
+ AvesMagnifierController coverController,
+ Size coverSize,
+ ImageProvider videoCoverUriImage,
+ ) magnifierBuilder;
+
+ const VideoCover({
+ super.key,
+ required this.mainEntry,
+ required this.pageEntry,
+ required this.magnifierController,
+ required this.videoController,
+ required this.videoDisplaySize,
+ required this.onTap,
+ required this.magnifierBuilder,
+ });
+
+ @override
+ State<VideoCover> createState() => _VideoCoverState();
+}
+
+class _VideoCoverState extends State<VideoCover> {
+ ImageStream? _videoCoverStream;
+ late ImageStreamListener _videoCoverStreamListener;
+ final ValueNotifier<ImageInfo?> _videoCoverInfoNotifier = ValueNotifier(null);
+
+ AvesMagnifierController? _dismissedCoverMagnifierController;
+
+ AvesMagnifierController get dismissedCoverMagnifierController {
+ _dismissedCoverMagnifierController ??= AvesMagnifierController();
+ return _dismissedCoverMagnifierController!;
+ }
+
+ AvesEntry get mainEntry => widget.mainEntry;
+
+ AvesEntry get entry => widget.pageEntry;
+
+ AvesMagnifierController get magnifierController => widget.magnifierController;
+
+ AvesVideoController get videoController => widget.videoController;
+
+ Size get videoDisplaySize => widget.videoDisplaySize;
+
+ // use the high res photo as cover for the video part of a motion photo
+ ImageProvider get videoCoverUriImage => (mainEntry.isMotionPhoto ? mainEntry : entry).fullImage;
+
+ @override
+ void initState() {
+ super.initState();
+ _registerWidget(widget);
+ }
+
+ @override
+ void didUpdateWidget(covariant VideoCover oldWidget) {
+ super.didUpdateWidget(oldWidget);
+
+ if (oldWidget.pageEntry != widget.pageEntry) {
+ _unregisterWidget(oldWidget);
+ _registerWidget(widget);
+ }
+ }
+
+ @override
+ void dispose() {
+ _unregisterWidget(widget);
+ _dismissedCoverMagnifierController?.dispose();
+ _videoCoverInfoNotifier.dispose();
+ super.dispose();
+ }
+
+ void _registerWidget(VideoCover widget) {
+ _videoCoverStreamListener = ImageStreamListener((image, _) => _videoCoverInfoNotifier.value = image);
+ _videoCoverStream = videoCoverUriImage.resolve(ImageConfiguration.empty);
+ _videoCoverStream!.addListener(_videoCoverStreamListener);
+ }
+
+ void _unregisterWidget(VideoCover oldWidget) {
+ _videoCoverStream?.removeListener(_videoCoverStreamListener);
+ _videoCoverStream = null;
+ _videoCoverInfoNotifier.value = null;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ // fade out image to ease transition with the player
+ return StreamBuilder<VideoStatus>(
+ stream: videoController.statusStream,
+ builder: (context, snapshot) {
+ final showCover = !videoController.isReady;
+ return IgnorePointer(
+ ignoring: !showCover,
+ child: AnimatedOpacity(
+ opacity: showCover ? 1 : 0,
+ curve: Curves.easeInCirc,
+ duration: ADurations.viewerVideoPlayerTransition,
+ onEnd: () {
+ // while cover is fading out, the same controller is used for both the cover and the video,
+ // and both fire scale boundaries events, so we make sure that in the end
+ // the scale boundaries from the video are used after the cover is gone
+ final boundaries = magnifierController.scaleBoundaries;
+ if (boundaries != null) {
+ magnifierController.setScaleBoundaries(
+ boundaries.copyWith(
+ contentSize: videoDisplaySize,
+ ),
+ );
+ }
+ },
+ child: ValueListenableBuilder<ImageInfo?>(
+ valueListenable: _videoCoverInfoNotifier,
+ builder: (context, videoCoverInfo, child) {
+ if (videoCoverInfo != null) {
+ // full cover image may have a different size and different aspect ratio
+ final coverSize = Size(
+ videoCoverInfo.image.width.toDouble(),
+ videoCoverInfo.image.height.toDouble(),
+ );
+ // when the cover is the same size as the video itself
+ // (which is often the case when the cover is not embedded but just a frame),
+ // we can reuse the same magnifier and preserve its state when switching from cover to video
+ final coverController = showCover || coverSize == videoDisplaySize ? magnifierController : dismissedCoverMagnifierController;
+ return widget.magnifierBuilder(coverController, coverSize, videoCoverUriImage);
+ }
+
+ // default to cached thumbnail, if any
+ final extent = entry.cachedThumbnails.firstOrNull?.key.extent;
+ if (extent != null && extent > 0) {
+ return GestureDetector(
+ onTap: widget.onTap,
+ child: ThumbnailImage(
+ entry: entry,
+ extent: extent,
+ devicePixelRatio: MediaQuery.devicePixelRatioOf(context),
+ fit: BoxFit.contain,
+ showLoadingBackground: false,
+ ),
+ );
+ }
+
+ return const SizedBox();
+ },
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/lib/widgets/viewer/visual/video/subtitle/ass_parser.dart b/lib/widgets/viewer/visual/video/subtitle/ass_parser.dart
new file mode 100644
index 0000000..6b2da5b
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/subtitle/ass_parser.dart
@@ -0,0 +1,559 @@
+import 'package:aves/ref/unicode.dart';
+import 'package:aves/widgets/viewer/visual/video/subtitle/line.dart';
+import 'package:aves/widgets/viewer/visual/video/subtitle/span.dart';
+import 'package:aves/widgets/viewer/visual/video/subtitle/style.dart';
+import 'package:flutter/material.dart';
+
+class AssParser {
+ // the optional `*` before the tags seems to be used for inner overrides
+ // but specs for its usage are yet to be found
+ static final overridePattern = RegExp(r'{\*?(.*?)}');
+
+ static final tagPattern = RegExp(r'('
+ r'1a|2a|3a|4a'
+ r'|1c|2c|3c|4c'
+ r'|alpha|an|a'
+ r'|be|blur|bord|b'
+ r'|clip|c'
+ r'|fade|fad|fax|fay|fe|fn'
+ r'|frx|fry|frz|fr|fscx|fscy|fsp|fs'
+ r'|iclip|i'
+ r'|kf|ko|k|K'
+ r'|move|org'
+ r'|pbo|pos|p'
+ r'|q|r'
+ r'|shad|s'
+ r'|t|u'
+ r'|xbord|xshad|ybord|yshad'
+ r')');
+
+ // &H<aa>
+ static final alphaPattern = RegExp('&H(..)');
+
+ // &H<bb><gg><rr>&
+ static final colorPattern = RegExp('&H(..)(..)(..)&');
+
+ // (<X>,<Y>)
+ static final multiParamPattern = RegExp('\\((.*)\\)');
+
+ // e.g. m 937.5 472.67 b 937.5 472.67 937.25 501.25 960 501.5 960 501.5 937.5 500.33 937.5 529.83
+ static final pathPattern = RegExp(r'([mnlbspc])([.\s\d]+)');
+
+ // Parse text with ASS style overrides
+ // cf https://aegi.vmoe.info/docs/3.0/ASS_Tags/
+ // e.g. `And I'm like, "We can't {\i1}not{\i0} see it."`
+ // e.g. `{\fad(200,200)\blur3}lorem ipsum"`
+ // e.g. `{\fnCrapFLTSB\an9\bord5\fs70\c&H403A2D&\3c&HE5E5E8&\pos(1868.286,27.429)}lorem ipsum"`
+ static StyledSubtitleLine parse(String text, TextStyle baseStyle, double scale) {
+ final spans = <StyledSubtitleSpan>[];
+ var line = StyledSubtitleLine(spans: spans);
+ var extraStyle = const SubtitleStyle();
+ var textStyle = baseStyle;
+ var i = 0;
+ final overrideMatches = overridePattern.allMatches(text);
+ overrideMatches.forEach((overrideMatch) {
+ if (i != overrideMatch.start) {
+ final spanText = extraStyle.drawingPaths?.isNotEmpty == true ? null : _replaceChars(text.substring(i, overrideMatch.start));
+ spans.add(StyledSubtitleSpan(
+ textSpan: TextSpan(
+ text: spanText,
+ style: textStyle,
+ ),
+ extraStyle: extraStyle,
+ ));
+ }
+ i = overrideMatch.end;
+ final tags = overrideMatch.group(1);
+ tags?.split('\\').where((v) => v.isNotEmpty).forEach((tagWithParam) {
+ final tag = tagPattern.firstMatch(tagWithParam)?.group(1);
+ if (tag != null) {
+ final param = tagWithParam.substring(tag.length);
+ switch (tag) {
+ case 'alpha':
+ {
+ // \alpha: alpha of all components at once
+ final a = _parseAlpha(param);
+ if (a != null) {
+ textStyle = textStyle.copyWith(
+ color: textStyle.color?.withAlpha(a),
+ shadows: textStyle.shadows
+ ?.map((v) => Shadow(
+ color: v.color.withAlpha(a),
+ offset: v.offset,
+ blurRadius: v.blurRadius,
+ ))
+ .toList());
+ extraStyle = extraStyle.copyWith(
+ borderColor: extraStyle.borderColor?.withAlpha(a),
+ );
+ }
+ }
+ case '1a':
+ {
+ // \1a: fill alpha
+ final a = _parseAlpha(param);
+ if (a != null) textStyle = textStyle.copyWith(color: textStyle.color?.withAlpha(a));
+ }
+ case '3a':
+ {
+ // \3a: border alpha
+ final a = _parseAlpha(param);
+ if (a != null) extraStyle = extraStyle.copyWith(borderColor: extraStyle.borderColor?.withAlpha(a));
+ }
+ case '4a':
+ {
+ // \4a: shadow alpha
+ final a = _parseAlpha(param);
+ if (a != null) {
+ textStyle = textStyle.copyWith(
+ shadows: textStyle.shadows
+ ?.map((v) => Shadow(
+ color: v.color.withAlpha(a),
+ offset: v.offset,
+ blurRadius: v.blurRadius,
+ ))
+ .toList());
+ }
+ }
+ case 'a':
+ // \a: line alignment (legacy)
+ extraStyle = _copyWithAlignment(_parseLegacyAlignment(param), extraStyle);
+ case 'an':
+ // \an: line alignment
+ extraStyle = _copyWithAlignment(_parseNewAlignment(param), extraStyle);
+ case 'b':
+ {
+ // \b: bold
+ final weight = _parseFontWeight(param);
+ if (weight != null) textStyle = textStyle.copyWith(fontWeight: weight);
+ }
+ case 'be':
+ {
+ // \be: blurs the edges of the text
+ final times = int.tryParse(param);
+ if (times != null) extraStyle = extraStyle.copyWith(edgeBlur: times == 0 ? 0 : 1);
+ }
+ case 'blur':
+ {
+ // \blur: blurs the edges of the text (Gaussian kernel)
+ final strength = double.tryParse(param);
+ if (strength != null) extraStyle = extraStyle.copyWith(edgeBlur: strength / 2);
+ }
+ case 'bord':
+ {
+ // \bord: border width
+ final size = double.tryParse(param);
+ if (size != null) extraStyle = extraStyle.copyWith(borderWidth: size);
+ }
+ case 'c':
+ case '1c':
+ {
+ // \c or \1c: fill color
+ final color = _parseColor(param);
+ if (color != null) {
+ textStyle = textStyle.copyWith(color: color.withValues(alpha: textStyle.color?.a ?? 1));
+ }
+ }
+ case '3c':
+ {
+ // \3c: border color
+ final color = _parseColor(param);
+ if (color != null) {
+ extraStyle = extraStyle.copyWith(
+ borderColor: color.withValues(alpha: extraStyle.borderColor?.a ?? 1),
+ );
+ }
+ }
+ case '4c':
+ {
+ // \4c: shadow color
+ final color = _parseColor(param);
+ if (color != null) {
+ textStyle = textStyle.copyWith(
+ shadows: textStyle.shadows
+ ?.map((v) => Shadow(
+ color: color.withValues(alpha: v.color.a),
+ offset: v.offset,
+ blurRadius: v.blurRadius,
+ ))
+ .toList());
+ }
+ }
+ case 'clip':
+ // \clip: clip (within rectangle or path)
+ line = line.copyWith(clip: _parseClip(param));
+ case 'fax':
+ {
+ final factor = double.tryParse(param);
+ // ignore subsequent shearing when line is positioned
+ if (factor != null && (line.position == null || extraStyle.shearX == null)) {
+ extraStyle = extraStyle.copyWith(shearX: factor);
+ }
+ }
+ case 'fay':
+ {
+ final factor = double.tryParse(param);
+ // ignore subsequent shearing when line is positioned
+ if (factor != null && (line.position == null || extraStyle.shearY == null)) {
+ extraStyle = extraStyle.copyWith(shearY: factor);
+ }
+ }
+ case 'fn':
+ {
+ final name = param;
+ // TODO TLAD [subtitles] extract fonts from attachment streams, and load these fonts in Flutter
+ if (name.isNotEmpty) textStyle = textStyle.copyWith(fontFamily: name);
+ }
+ case 'frx':
+ {
+ // \frx: text rotation (X axis)
+ final amount = double.tryParse(param);
+ if (amount != null) extraStyle = extraStyle.copyWith(rotationX: amount);
+ }
+ case 'fry':
+ {
+ // \fry: text rotation (Y axis)
+ final amount = double.tryParse(param);
+ if (amount != null) extraStyle = extraStyle.copyWith(rotationY: amount);
+ }
+ case 'fr':
+ case 'frz':
+ {
+ // \frz: text rotation (Z axis)
+ final amount = double.tryParse(param);
+ if (amount != null) extraStyle = extraStyle.copyWith(rotationZ: amount);
+ }
+ case 'fs':
+ {
+ // \fs: font size
+ final size = int.tryParse(param);
+ if (size != null) textStyle = textStyle.copyWith(fontSize: size * scale);
+ }
+ case 'fscx':
+ {
+ // \fscx: font scale (horizontal)
+ final scale = int.tryParse(param);
+ if (scale != null) extraStyle = extraStyle.copyWith(scaleX: scale.toDouble() / 100);
+ }
+ case 'fscy':
+ {
+ // \fscx: font scale (vertical)
+ final scale = int.tryParse(param);
+ if (scale != null) extraStyle = extraStyle.copyWith(scaleY: scale.toDouble() / 100);
+ }
+ case 'fsp':
+ {
+ // \fsp: letter spacing
+ final spacing = double.tryParse(param);
+ textStyle = textStyle.copyWith(letterSpacing: spacing);
+ }
+ case 'i':
+ // \i: italics
+ textStyle = textStyle.copyWith(fontStyle: param == '1' ? FontStyle.italic : FontStyle.normal);
+ case 'p':
+ {
+ // \p drawing paths
+ final scale = int.tryParse(param);
+ if (scale != null) {
+ if (scale > 0) {
+ final start = overrideMatch.end;
+ final end = text.indexOf('{', start);
+ final commands = text.substring(start, end == -1 ? null : end);
+ extraStyle = extraStyle.copyWith(drawingPaths: _parsePaths(commands, scale));
+ } else {
+ extraStyle = extraStyle.copyWith(drawingPaths: null);
+ }
+ }
+ }
+ case 'pos':
+ {
+ // \pos: line position
+ final match = multiParamPattern.firstMatch(param);
+ if (match != null) {
+ final g = match.group(1);
+ if (g != null) {
+ final params = g.split(',');
+ if (params.length == 2) {
+ final x = double.tryParse(params[0]);
+ final y = double.tryParse(params[1]);
+ if (x != null && y != null) {
+ line = line.copyWith(position: Offset(x, y));
+ }
+ }
+ }
+ }
+ }
+ case 'r':
+ // \r: reset
+ textStyle = baseStyle;
+ case 's':
+ // \s: strikeout
+ textStyle = textStyle.copyWith(decoration: param == '1' ? TextDecoration.lineThrough : TextDecoration.none);
+ case 'u':
+ // \u: underline
+ textStyle = textStyle.copyWith(decoration: param == '1' ? TextDecoration.underline : TextDecoration.none);
+ // TODO TLAD [subtitles] SHOULD support the following
+ case 'shad':
+ case 't': // \t: animated transform
+ case 'xshad':
+ case 'yshad':
+ // line props: \pos, \move, \clip, \iclip, \org, \fade and \fad
+ case 'iclip': // \iclip: clip (inverse)
+ case 'fad': // \fad: fade
+ case 'fade': // \fade: fade (complex)
+ case 'move': // \move: movement
+ case 'org': // \org: rotation origin
+ // TODO TLAD [subtitles] MAY support the following
+ case 'fe': // \fe: font encoding
+ case 'pbo': // \pbo: baseline offset
+ case 'q': // \q: wrap style
+ // border size
+ case 'xbord':
+ case 'ybord':
+ // karaoke
+ case '2a':
+ case '2c':
+ case 'k':
+ case 'K':
+ case 'kf':
+ case 'ko':
+ default:
+ debugPrint('unhandled ASS tag=$tag');
+ }
+ }
+ });
+ });
+ if (i != text.length) {
+ final spanText = extraStyle.drawingPaths?.isNotEmpty == true ? null : _replaceChars(text.substring(i));
+ spans.add(StyledSubtitleSpan(
+ textSpan: TextSpan(
+ text: spanText,
+ style: textStyle,
+ ),
+ extraStyle: extraStyle,
+ ));
+ }
+ return line;
+ }
+
+ static SubtitleStyle _copyWithAlignment(Alignment? alignment, SubtitleStyle extraStyle) {
+ if (alignment == null) return extraStyle;
+
+ var hAlign = TextAlign.center;
+ var vAlign = TextAlignVertical.bottom;
+ if (alignment.x < 0) {
+ hAlign = TextAlign.left;
+ } else if (alignment.x > 0) {
+ hAlign = TextAlign.right;
+ }
+ if (alignment.y < 0) {
+ vAlign = TextAlignVertical.top;
+ } else if (alignment.y == 0) {
+ vAlign = TextAlignVertical.center;
+ }
+ return extraStyle.copyWith(
+ hAlign: hAlign,
+ vAlign: vAlign,
+ );
+ }
+
+ static String _replaceChars(String text) => text.replaceAll(r'\h', UniChars.noBreakSpace).replaceAll(r'\N', '\n');
+
+ static int? _parseAlpha(String param) {
+ final match = alphaPattern.firstMatch(param);
+ if (match != null) {
+ final as = match.group(1);
+ final ai = as != null ? int.tryParse(as, radix: 16) : null;
+ if (ai != null) {
+ return 0xFF - ai;
+ }
+ }
+ return null;
+ }
+
+ static Color? _parseColor(String param) {
+ final match = colorPattern.firstMatch(param);
+ if (match != null) {
+ final bs = match.group(1);
+ final gs = match.group(2);
+ final rs = match.group(3);
+ final rgb = int.tryParse('ff$rs$gs$bs', radix: 16);
+ if (rgb != null) {
+ return Color(rgb);
+ }
+ }
+ return null;
+ }
+
+ static FontWeight? _parseFontWeight(String param) {
+ switch (int.tryParse(param)) {
+ case 0:
+ return FontWeight.normal;
+ case 1:
+ return FontWeight.bold;
+ case 100:
+ return FontWeight.w100;
+ case 200:
+ return FontWeight.w200;
+ case 300:
+ return FontWeight.w300;
+ case 400:
+ return FontWeight.w400;
+ case 500:
+ return FontWeight.w500;
+ case 600:
+ return FontWeight.w600;
+ case 700:
+ return FontWeight.w700;
+ case 800:
+ return FontWeight.w800;
+ case 900:
+ return FontWeight.w900;
+ default:
+ return null;
+ }
+ }
+
+ static Alignment? _parseNewAlignment(String param) {
+ switch (int.tryParse(param)) {
+ case 1:
+ return Alignment.bottomLeft;
+ case 2:
+ return Alignment.bottomCenter;
+ case 3:
+ return Alignment.bottomRight;
+ case 4:
+ return Alignment.centerLeft;
+ case 5:
+ return Alignment.center;
+ case 6:
+ return Alignment.centerRight;
+ case 7:
+ return Alignment.topLeft;
+ case 8:
+ return Alignment.topCenter;
+ case 9:
+ return Alignment.topRight;
+ default:
+ return null;
+ }
+ }
+
+ static Alignment? _parseLegacyAlignment(String param) {
+ switch (int.tryParse(param)) {
+ case 1:
+ return Alignment.bottomLeft;
+ case 2:
+ return Alignment.bottomCenter;
+ case 3:
+ return Alignment.bottomRight;
+ case 5:
+ return Alignment.topLeft;
+ case 6:
+ return Alignment.topCenter;
+ case 7:
+ return Alignment.topRight;
+ case 9:
+ return Alignment.centerLeft;
+ case 10:
+ return Alignment.center;
+ case 11:
+ return Alignment.centerRight;
+ default:
+ return null;
+ }
+ }
+
+ static List<Path> _parsePaths(String commands, int scale) {
+ final paths = <Path>[];
+ Path? path;
+ pathPattern.allMatches(commands).forEach((match) {
+ if (match.groupCount == 2) {
+ final command = match.group(1)!;
+ final params = match.group(2)!.trim().split(' ').map(double.tryParse).nonNulls.map((v) => v / scale).toList();
+ switch (command) {
+ case 'b':
+ if (path != null) {
+ const bParamCount = 6;
+ final steps = (params.length / bParamCount).floor();
+ for (var i = 0; i < steps; i++) {
+ final points = params.skip(i * bParamCount).take(bParamCount).toList();
+ path!.cubicTo(points[0], points[1], points[2], points[3], points[4], points[5]);
+ }
+ }
+ case 'c':
+ if (path != null) {
+ path!.close();
+ }
+ path = null;
+ case 'l':
+ if (path != null) {
+ const lParamCount = 2;
+ final steps = (params.length / lParamCount).floor();
+ for (var i = 0; i < steps; i++) {
+ final points = params.skip(i * lParamCount).take(lParamCount).toList();
+ path!.lineTo(points[0], points[1]);
+ }
+ }
+ case 'm':
+ if (params.length == 2) {
+ if (path != null) {
+ path!.close();
+ }
+ path = Path();
+ paths.add(path!);
+ path!.moveTo(params[0], params[1]);
+ }
+ case 'n':
+ if (params.length == 2 && path != null) {
+ path!.moveTo(params[0], params[1]);
+ }
+ case 's':
+ case 'p':
+ debugPrint('unhandled ASS drawing command=$command');
+ }
+ }
+ });
+ if (path != null) {
+ path!.close();
+ }
+ return paths;
+ }
+
+ static List<Path>? _parseClip(String param) {
+ List<Path>? paths;
+ final match = multiParamPattern.firstMatch(param);
+ if (match != null) {
+ final g = match.group(1);
+ if (g != null) {
+ final params = g.split(',');
+ if (params.length == 4) {
+ final points = params.map(double.tryParse).nonNulls.toList();
+ if (points.length == 4) {
+ paths = [
+ Path()
+ ..addRect(Rect.fromPoints(
+ Offset(points[0], points[1]),
+ Offset(points[2], points[3]),
+ ))
+ ];
+ }
+ } else {
+ int? scale;
+ String? commands;
+ if (params.length == 1) {
+ scale = 1;
+ commands = params[0];
+ } else if (params.length == 2) {
+ scale = int.tryParse(params[0]);
+ commands = params[1];
+ }
+ if (scale != null && commands != null) {
+ paths = _parsePaths(commands, scale);
+ }
+ }
+ }
+ }
+ return paths;
+ }
+}
diff --git a/lib/widgets/viewer/visual/video/subtitle/line.dart b/lib/widgets/viewer/visual/video/subtitle/line.dart
new file mode 100644
index 0000000..f7a213b
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/subtitle/line.dart
@@ -0,0 +1,40 @@
+import 'package:aves/widgets/viewer/visual/video/subtitle/span.dart';
+import 'package:equatable/equatable.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart';
+
+@immutable
+class StyledSubtitleLine extends Equatable with Diagnosticable {
+ final List<StyledSubtitleSpan> spans;
+ final List<Path>? clip;
+ final Offset? position;
+
+ @override
+ List<Object?> get props => [spans, clip, position];
+
+ const StyledSubtitleLine({
+ required this.spans,
+ this.clip,
+ this.position,
+ });
+
+ StyledSubtitleLine copyWith({
+ List<StyledSubtitleSpan>? spans,
+ List<Path>? clip,
+ Offset? position,
+ }) {
+ return StyledSubtitleLine(
+ spans: spans ?? this.spans,
+ clip: clip ?? this.clip,
+ position: position ?? this.position,
+ );
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(DiagnosticsProperty<List<StyledSubtitleSpan>>('spans', spans));
+ properties.add(DiagnosticsProperty<List<Path>>('clip', clip));
+ properties.add(DiagnosticsProperty<Offset>('position', position));
+ }
+}
diff --git a/lib/widgets/viewer/visual/video/subtitle/span.dart b/lib/widgets/viewer/visual/video/subtitle/span.dart
new file mode 100644
index 0000000..0f58705
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/subtitle/span.dart
@@ -0,0 +1,35 @@
+import 'package:aves/widgets/viewer/visual/video/subtitle/style.dart';
+import 'package:equatable/equatable.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart';
+
+@immutable
+class StyledSubtitleSpan extends Equatable with Diagnosticable {
+ final TextSpan textSpan;
+ final SubtitleStyle extraStyle;
+
+ @override
+ List<Object?> get props => [textSpan, extraStyle];
+
+ const StyledSubtitleSpan({
+ required this.textSpan,
+ required this.extraStyle,
+ });
+
+ StyledSubtitleSpan copyWith({
+ TextSpan? textSpan,
+ SubtitleStyle? extraStyle,
+ }) {
+ return StyledSubtitleSpan(
+ textSpan: textSpan ?? this.textSpan,
+ extraStyle: extraStyle ?? this.extraStyle,
+ );
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(DiagnosticsProperty<TextSpan>('textSpan', textSpan));
+ properties.add(DiagnosticsProperty<SubtitleStyle>('extraStyle', extraStyle));
+ }
+}
diff --git a/lib/widgets/viewer/visual/video/subtitle/style.dart b/lib/widgets/viewer/visual/video/subtitle/style.dart
new file mode 100644
index 0000000..3700eb1
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/subtitle/style.dart
@@ -0,0 +1,101 @@
+import 'package:equatable/equatable.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart';
+
+@immutable
+class SubtitleStyle extends Equatable with Diagnosticable {
+ final TextAlign? hAlign;
+ final TextAlignVertical? vAlign;
+ final Color? borderColor;
+ final double? borderWidth, edgeBlur, rotationX, rotationY, rotationZ, scaleX, scaleY, shearX, shearY;
+ final List<Path>? drawingPaths;
+
+ bool get rotating => (rotationX ?? 0) != 0 || (rotationY ?? 0) != 0 || (rotationZ ?? 0) != 0;
+
+ bool get scaling => (scaleX ?? 1) != 1 || (scaleY ?? 1) != 1;
+
+ bool get shearing => (shearX ?? 0) != 0 || (shearY ?? 0) != 0;
+
+ @override
+ List<Object?> get props => [
+ hAlign,
+ vAlign,
+ borderColor,
+ borderWidth,
+ edgeBlur,
+ rotationX,
+ rotationY,
+ rotationZ,
+ scaleX,
+ scaleY,
+ shearX,
+ shearY,
+ drawingPaths?.length,
+ ];
+
+ const SubtitleStyle({
+ this.hAlign,
+ this.vAlign,
+ this.borderColor,
+ this.borderWidth,
+ this.edgeBlur,
+ this.rotationX,
+ this.rotationY,
+ this.rotationZ,
+ this.scaleX,
+ this.scaleY,
+ this.shearX,
+ this.shearY,
+ this.drawingPaths,
+ });
+
+ SubtitleStyle copyWith({
+ TextAlign? hAlign,
+ TextAlignVertical? vAlign,
+ Color? borderColor,
+ double? borderWidth,
+ double? edgeBlur,
+ double? rotationX,
+ double? rotationY,
+ double? rotationZ,
+ double? scaleX,
+ double? scaleY,
+ double? shearX,
+ double? shearY,
+ List<Path>? drawingPaths,
+ }) {
+ return SubtitleStyle(
+ hAlign: hAlign ?? this.hAlign,
+ vAlign: vAlign ?? this.vAlign,
+ borderColor: borderColor ?? this.borderColor,
+ borderWidth: borderWidth ?? this.borderWidth,
+ edgeBlur: edgeBlur ?? this.edgeBlur,
+ rotationX: rotationX ?? this.rotationX,
+ rotationY: rotationY ?? this.rotationY,
+ rotationZ: rotationZ ?? this.rotationZ,
+ scaleX: scaleX ?? this.scaleX,
+ scaleY: scaleY ?? this.scaleY,
+ shearX: shearX ?? this.shearX,
+ shearY: shearY ?? this.shearY,
+ drawingPaths: drawingPaths ?? this.drawingPaths,
+ );
+ }
+
+ @override
+ void debugFillProperties(DiagnosticPropertiesBuilder properties) {
+ super.debugFillProperties(properties);
+ properties.add(EnumProperty<TextAlign>('hAlign', hAlign));
+ properties.add(DiagnosticsProperty<TextAlignVertical>('vAlign', vAlign));
+ properties.add(ColorProperty('borderColor', borderColor));
+ properties.add(DoubleProperty('borderWidth', borderWidth));
+ properties.add(DoubleProperty('edgeBlur', edgeBlur));
+ properties.add(DoubleProperty('rotationX', rotationX));
+ properties.add(DoubleProperty('rotationY', rotationY));
+ properties.add(DoubleProperty('rotationZ', rotationZ));
+ properties.add(DoubleProperty('scaleX', scaleX));
+ properties.add(DoubleProperty('scaleY', scaleY));
+ properties.add(DoubleProperty('shearX', shearX));
+ properties.add(DoubleProperty('shearY', shearY));
+ properties.add(DiagnosticsProperty<List<Path>>('drawingPaths', drawingPaths));
+ }
+}
diff --git a/lib/widgets/viewer/visual/video/subtitle/subtitle.dart b/lib/widgets/viewer/visual/video/subtitle/subtitle.dart
new file mode 100644
index 0000000..cbf10e7
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/subtitle/subtitle.dart
@@ -0,0 +1,337 @@
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/entry/extensions/props.dart';
+import 'package:aves/model/settings/enums/subtitle_position.dart';
+import 'package:aves/model/settings/settings.dart';
+import 'package:aves/model/viewer/view_state.dart';
+import 'package:aves/widgets/common/basic/text/background_painter.dart';
+import 'package:aves/widgets/common/basic/text/outlined.dart';
+import 'package:aves/widgets/viewer/visual/video/subtitle/ass_parser.dart';
+import 'package:aves/widgets/viewer/visual/video/subtitle/span.dart';
+import 'package:aves/widgets/viewer/visual/video/subtitle/style.dart';
+import 'package:aves_video/aves_video.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:latlong2/latlong.dart' as angles;
+import 'package:provider/provider.dart';
+
+class VideoSubtitles extends StatelessWidget {
+ final AvesEntry entry;
+ final AvesVideoController controller;
+ final ValueNotifier<ViewState> viewStateNotifier;
+ final bool debugMode;
+
+ static const baseShadowOffset = Offset(1, 1);
+
+ const VideoSubtitles({
+ super.key,
+ required this.entry,
+ required this.controller,
+ required this.viewStateNotifier,
+ this.debugMode = false,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ return ValueListenableBuilder<double?>(
+ valueListenable: controller.sarNotifier,
+ builder: (context, sar, child) {
+ final videoDisplaySize = entry.videoDisplaySize(sar);
+
+ return IgnorePointer(
+ child: Consumer<Settings>(
+ builder: (context, settings, child) {
+ final baseTextAlign = settings.subtitleTextAlignment;
+ final baseTextAlignY = settings.subtitleTextPosition.toTextAlignVertical();
+ final baseOutlineWidth = settings.subtitleShowOutline ? 1 : 0;
+ final baseOutlineColor = Colors.black.withValues(alpha: settings.subtitleTextColor.a);
+ final baseShadows = [
+ Shadow(
+ color: baseOutlineColor,
+ offset: baseShadowOffset,
+ ),
+ ];
+ final baseStyle = TextStyle(
+ color: settings.subtitleTextColor,
+ fontSize: settings.subtitleFontSize,
+ shadows: settings.subtitleShowOutline ? baseShadows : null,
+ );
+
+ final viewportSize = MediaQuery.sizeOf(context);
+ final isPortrait = MediaQuery.orientationOf(context) == Orientation.portrait;
+ final bottom = isPortrait ? .5 : .8;
+ return ValueListenableBuilder<ViewState>(
+ valueListenable: viewStateNotifier,
+ builder: (context, viewState, child) {
+ final viewPosition = viewState.position;
+ final viewScale = viewState.scale ?? 1;
+ final viewSize = videoDisplaySize * viewScale;
+ final viewOffset = Offset(
+ (viewportSize.width - viewSize.width) / 2,
+ (viewportSize.height - viewSize.height) / 2,
+ );
+
+ return StreamBuilder<String?>(
+ stream: controller.timedTextStream,
+ builder: (context, snapshot) {
+ final text = snapshot.data;
+ if (text == null) return const SizedBox();
+
+ if (debugMode) {
+ return Padding(
+ padding: const EdgeInsets.only(top: 100.0),
+ child: Align(
+ alignment: Alignment.topLeft,
+ child: OutlinedText(
+ textSpans: [
+ TextSpan(
+ text: text,
+ style: const TextStyle(fontSize: 14),
+ )
+ ],
+ outlineWidth: 1,
+ outlineColor: Colors.black,
+ ),
+ ),
+ );
+ }
+
+ final styledLine = AssParser.parse(text, baseStyle, viewScale);
+ final position = styledLine.position;
+ final clip = styledLine.clip;
+ final styledSpans = styledLine.spans;
+ final byExtraStyle = groupBy<StyledSubtitleSpan, SubtitleStyle>(styledSpans, (v) => v.extraStyle);
+ return Stack(
+ children: byExtraStyle.entries.map((kv) {
+ final extraStyle = kv.key;
+ final spans = kv.value.map((v) {
+ final span = v.textSpan;
+ final style = span.style;
+ if (position == null || style == null) return span;
+
+ final letterSpacing = style.letterSpacing;
+ final shadows = style.shadows;
+ return TextSpan(
+ text: span.text,
+ style: style.copyWith(
+ letterSpacing: letterSpacing != null ? letterSpacing * viewScale : null,
+ shadows: shadows
+ ?.map((v) => Shadow(
+ color: v.color,
+ offset: v.offset * viewScale,
+ blurRadius: v.blurRadius * viewScale,
+ ))
+ .toList(),
+ ),
+ );
+ }).toList();
+ final drawingPaths = extraStyle.drawingPaths;
+ final textHAlign = extraStyle.hAlign ?? (position != null ? TextAlign.center : baseTextAlign);
+ final textVAlign = extraStyle.vAlign ?? (position != null ? TextAlignVertical.bottom : baseTextAlignY);
+
+ Widget child;
+ if (drawingPaths != null) {
+ child = CustomPaint(
+ painter: SubtitlePathPainter(
+ paths: drawingPaths,
+ scale: viewScale,
+ fillColor: spans.firstOrNull?.style?.color ?? Colors.white,
+ strokeColor: extraStyle.borderColor,
+ ),
+ );
+ } else {
+ final outlineWidth = extraStyle.borderWidth ?? (extraStyle.edgeBlur != null ? 2 : 1);
+ child = OutlinedText(
+ textSpans: spans,
+ outlineWidth: outlineWidth * (position != null ? viewScale : baseOutlineWidth),
+ outlineColor: extraStyle.borderColor ?? baseOutlineColor,
+ outlineBlurSigma: extraStyle.edgeBlur ?? 0,
+ textAlign: textHAlign,
+ );
+ }
+
+ var transform = Matrix4.identity();
+
+ if (position != null) {
+ final paragraph = RenderParagraph(
+ TextSpan(children: spans),
+ textDirection: TextDirection.ltr,
+ textScaler: MediaQuery.textScalerOf(context),
+ )..layout(const BoxConstraints());
+ final textWidth = paragraph.getMaxIntrinsicWidth(double.infinity);
+ final textHeight = paragraph.getMaxIntrinsicHeight(double.infinity);
+ paragraph.dispose();
+
+ late double anchorOffsetX, anchorOffsetY;
+ switch (textHAlign) {
+ case TextAlign.left:
+ anchorOffsetX = 0;
+ case TextAlign.right:
+ anchorOffsetX = -textWidth;
+ case TextAlign.center:
+ default:
+ anchorOffsetX = -textWidth / 2;
+ }
+ switch (textVAlign) {
+ case TextAlignVertical.top:
+ anchorOffsetY = 0;
+ case TextAlignVertical.center:
+ anchorOffsetY = -textHeight / 2;
+ case TextAlignVertical.bottom:
+ anchorOffsetY = -textHeight;
+ }
+ final alignOffset = Offset(anchorOffsetX, anchorOffsetY);
+ final lineOffset = position * viewScale + viewPosition;
+ final translateOffset = viewOffset + lineOffset + alignOffset;
+ transform.translate(translateOffset.dx, translateOffset.dy);
+ }
+
+ if (extraStyle.rotating) {
+ // for perspective
+ transform.setEntry(3, 2, 0.001);
+ final x = -angles.degToRadian(extraStyle.rotationX ?? 0);
+ final y = -angles.degToRadian(extraStyle.rotationY ?? 0);
+ final z = -angles.degToRadian(extraStyle.rotationZ ?? 0);
+ if (x != 0) transform.rotateX(x);
+ if (y != 0) transform.rotateY(y);
+ if (z != 0) transform.rotateZ(z);
+ }
+ if (extraStyle.scaling) {
+ final x = extraStyle.scaleX ?? 1;
+ final y = extraStyle.scaleY ?? 1;
+ transform.scale(x, y);
+ }
+ if (extraStyle.shearing) {
+ final x = extraStyle.shearX ?? 0;
+ final y = extraStyle.shearY ?? 0;
+ transform.multiply(Matrix4(1, y, 0, 0, x, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1));
+ }
+
+ if (!transform.isIdentity()) {
+ child = Transform(
+ transform: transform,
+ alignment: Alignment.center,
+ child: child,
+ );
+ }
+
+ if (position == null) {
+ late double alignX;
+ switch (textHAlign) {
+ case TextAlign.left:
+ alignX = -1;
+ case TextAlign.right:
+ alignX = 1;
+ case TextAlign.center:
+ default:
+ alignX = 0;
+ }
+ late double alignY;
+ switch (textVAlign) {
+ case TextAlignVertical.top:
+ alignY = -bottom;
+ case TextAlignVertical.center:
+ alignY = 0;
+ case TextAlignVertical.bottom:
+ default:
+ alignY = bottom;
+ }
+ child = Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Align(
+ alignment: Alignment(alignX, alignY),
+ child: TextBackgroundPainter(
+ spans: spans,
+ style: DefaultTextStyle.of(context).style.merge(spans.first.style!.copyWith(
+ backgroundColor: settings.subtitleBackgroundColor,
+ )),
+ textAlign: textHAlign,
+ child: child,
+ ),
+ ),
+ );
+ }
+
+ if (clip != null) {
+ final clipOffset = viewOffset + viewPosition;
+ final matrix = Matrix4.identity()
+ ..translate(clipOffset.dx, clipOffset.dy)
+ ..scale(viewScale, viewScale);
+ final transform = matrix.storage;
+ child = ClipPath(
+ clipper: SubtitlePathClipper(
+ paths: clip.map((v) => v.transform(transform)).toList(),
+ scale: viewScale,
+ ),
+ child: child,
+ );
+ }
+
+ return child;
+ }).toList(),
+ );
+ },
+ );
+ },
+ );
+ },
+ ),
+ );
+ },
+ );
+ }
+}
+
+class SubtitlePathPainter extends CustomPainter {
+ final List<Path> paths;
+ final double scale;
+ final Paint? fillPaint, strokePaint;
+
+ SubtitlePathPainter({
+ required this.paths,
+ required this.scale,
+ required Color? fillColor,
+ required Color? strokeColor,
+ }) : fillPaint = fillColor != null
+ ? (Paint()
+ ..style = PaintingStyle.fill
+ ..color = fillColor)
+ : null,
+ strokePaint = strokeColor != null
+ ? (Paint()
+ ..style = PaintingStyle.stroke
+ ..color = strokeColor)
+ : null;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ canvas.scale(scale, scale);
+ paths.forEach((path) {
+ if (fillPaint != null) {
+ canvas.drawPath(path, fillPaint!);
+ }
+ if (strokePaint != null) {
+ canvas.drawPath(path, strokePaint!);
+ }
+ });
+ }
+
+ @override
+ bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
+}
+
+class SubtitlePathClipper extends CustomClipper<Path> {
+ final List<Path> paths;
+ final double scale;
+
+ const SubtitlePathClipper({
+ required this.paths,
+ required this.scale,
+ });
+
+ @override
+ Path getClip(Size size) => paths.firstOrNull ?? Path();
+
+ @override
+ bool shouldReclip(covariant CustomClipper<Path> oldClipper) => true;
+}
diff --git a/lib/widgets/viewer/visual/video/swipe_action.dart b/lib/widgets/viewer/visual/video/swipe_action.dart
new file mode 100644
index 0000000..da3a6b1
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/swipe_action.dart
@@ -0,0 +1,137 @@
+import 'dart:async';
+
+import 'package:aves/theme/icons.dart';
+import 'package:aves/widgets/aves_app.dart';
+import 'package:decorated_icon/decorated_icon.dart';
+import 'package:flutter/material.dart';
+import 'package:volume_controller/volume_controller.dart';
+
+enum SwipeAction { brightness, volume }
+
+extension ExtraSwipeAction on SwipeAction {
+ Future<double> get() {
+ switch (this) {
+ case SwipeAction.brightness:
+ return AvesApp.screenBrightness?.application ?? Future.value(1);
+ case SwipeAction.volume:
+ return VolumeController.instance.getVolume();
+ }
+ }
+
+ Future<void> set(double value) async {
+ switch (this) {
+ case SwipeAction.brightness:
+ await AvesApp.screenBrightness?.setApplicationScreenBrightness(value);
+ case SwipeAction.volume:
+ VolumeController.instance.showSystemUI = false;
+ await VolumeController.instance.setVolume(value);
+ }
+ }
+}
+
+class SwipeActionFeedback extends StatelessWidget {
+ final SwipeAction action;
+ final ValueNotifier<double?> valueNotifier;
+
+ const SwipeActionFeedback({
+ super.key,
+ required this.action,
+ required this.valueNotifier,
+ });
+
+ static const double width = 32;
+ static const double height = 160;
+ static const Radius radius = Radius.circular(width / 2);
+ static const double borderWidth = 2;
+ static const Color borderColor = Colors.white;
+ static final Color fillColor = Colors.white.withValues(alpha: .8);
+ static final Color backgroundColor = Colors.black.withValues(alpha: .2);
+ static final Color innerBorderColor = Colors.black.withValues(alpha: .5);
+ static const Color iconColor = Colors.white;
+ static const Color shadowColor = Colors.black;
+
+ @override
+ Widget build(BuildContext context) {
+ return Center(
+ child: ValueListenableBuilder<double?>(
+ valueListenable: valueNotifier,
+ builder: (context, value, child) {
+ if (value == null) return const SizedBox();
+
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _buildIcon(_getMaxIcon()),
+ Container(
+ decoration: BoxDecoration(
+ color: backgroundColor,
+ border: Border.all(
+ width: borderWidth * 2,
+ color: innerBorderColor,
+ ),
+ borderRadius: const BorderRadius.all(radius),
+ ),
+ foregroundDecoration: BoxDecoration(
+ border: Border.all(
+ color: borderColor,
+ width: borderWidth,
+ ),
+ borderRadius: const BorderRadius.all(radius),
+ ),
+ width: width,
+ height: height,
+ child: ClipRRect(
+ borderRadius: const BorderRadius.all(radius),
+ child: Align(
+ alignment: Alignment.bottomCenter,
+ child: Container(
+ color: fillColor,
+ width: width,
+ height: height * value,
+ ),
+ ),
+ ),
+ ),
+ _buildIcon(_getMinIcon()),
+ ],
+ );
+ },
+ ),
+ );
+ }
+
+ Widget _buildIcon(IconData icon) {
+ return Padding(
+ padding: const EdgeInsets.all(16),
+ child: DecoratedIcon(
+ icon,
+ size: width,
+ color: iconColor,
+ shadows: const [
+ Shadow(
+ color: shadowColor,
+ blurRadius: 4,
+ )
+ ],
+ ),
+ );
+ }
+
+ IconData _getMinIcon() {
+ switch (action) {
+ case SwipeAction.brightness:
+ return AIcons.brightnessMin;
+ case SwipeAction.volume:
+ return AIcons.volumeMin;
+ }
+ }
+
+ IconData _getMaxIcon() {
+ switch (action) {
+ case SwipeAction.brightness:
+ return AIcons.brightnessMax;
+ case SwipeAction.volume:
+ return AIcons.volumeMax;
+ }
+ }
+}
diff --git a/lib/widgets/viewer/visual/video/video_view.dart b/lib/widgets/viewer/visual/video/video_view.dart
new file mode 100644
index 0000000..c06c060
--- /dev/null
+++ b/lib/widgets/viewer/visual/video/video_view.dart
@@ -0,0 +1,61 @@
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves_video/aves_video.dart';
+import 'package:flutter/material.dart';
+
+class VideoView extends StatefulWidget {
+ final AvesEntry entry;
+ final AvesVideoController controller;
+
+ const VideoView({
+ super.key,
+ required this.entry,
+ required this.controller,
+ });
+
+ @override
+ State<StatefulWidget> createState() => _VideoViewState();
+}
+
+class _VideoViewState extends State<VideoView> {
+ AvesEntry get entry => widget.entry;
+
+ AvesVideoController get controller => widget.controller;
+
+ @override
+ void initState() {
+ super.initState();
+ _registerWidget(widget);
+ }
+
+ @override
+ void didUpdateWidget(covariant VideoView oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ _unregisterWidget(oldWidget);
+ _registerWidget(widget);
+ }
+
+ @override
+ void dispose() {
+ _unregisterWidget(widget);
+ super.dispose();
+ }
+
+ void _registerWidget(VideoView widget) {
+ widget.controller.playCompletedListenable.addListener(_onPlayCompleted);
+ }
+
+ void _unregisterWidget(VideoView widget) {
+ widget.controller.playCompletedListenable.removeListener(_onPlayCompleted);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return StreamBuilder<VideoStatus>(
+ stream: controller.statusStream,
+ builder: (context, snapshot) => controller.isReady ? controller.buildPlayerWidget(context) : const SizedBox(),
+ );
+ }
+
+ // not called when looping
+ void _onPlayCompleted() => controller.seekTo(0);
+}