frosty/lib/theme.dart
Tommy Chow f2b932bc93
feat(video,chat): native player, ad-break awareness, chat send/delay reliability, and tab redesign (#567)
Squash-merge commit. Covers four areas: native video player, chat reliability, multi-tab, and hardening.

## Native video player
- Direct HLS playback via `better_native_video_player` (forked from `plug-and-pay/flutter-native-video-player`, patched on `frosty-patches` branch)
- Twitch GQL playback token fetching with platform cookie extraction (iOS Swift + Android Kotlin plugins) for authenticated streams
- Quality selection (source, 720p, 480p, 360p, 160p, audio-only) persisted per channel
- Picture-in-picture: iOS automatic inline PiP, Android auto-PiP on API 31+ guarded against older devices
- Latency polling, chat latency sync, stall detection/recovery, startup auto-pause recovery, watchdog timers
- **Twitch stitched-ad break detection** (HLS `EXT-X-DATERANGE`) on both platforms, emitting `adBreakChanged` so the host suspends latency/stall recovery and chat sync during ads (program-date-time is unreliable then). Matches `CLASS="twitch-stitched-ad"` / `ID="stitched-ad-"` **and** the `X-TV-TWITCH-AD-*` attribute prefix (the durable signal streamlink/yt-dlp use)
- Shared `VideoPlayerInterface` so WebView and native paths are interchangeable via settings toggle
- `PlaybackAccessToken` model, `TwitchGqlApi` client

## Chat delay & send reliability
- **Optimistic send-finalize**: Twitch acks a sent message with a per-PRIVMSG USERSTATE (not an echo), which it can intermittently drop — more so under a long chat delay. A missing ack no longer shows a false "message may not have been sent" error; the send is finalized optimistically (local echo rendered), and only genuine rejection NOTICEs surface an error. Ack timeout scaled by the chat delay.
- **Per-line chat-delay bypass**: control/state lines (USERSTATE/ROOMSTATE/GLOBALUSERSTATE), rejection NOTICEs, the reconnect notice, and untagged server lines bypass the delay so send-acks and PONGs aren't stalled; only displayable chat content is delayed, staying in sync with delayed video.
- **Measured chat bottom-bar height**: the message list reflows to the composer's real measured height, fixing the input overlapping messages when a long message expands it (replaces a fixed-constant estimate).
- IRC tag parsing handles valueless and escaped tags per the IRCv3 message-tags spec (fixes a recent-messages RangeError on certain tags).

## Chat / multi-tab
- Redesigned tab chips: unread dot indicator, chips dim until WebSocket connects
- Animated tab options popover replacing `MenuAnchor` (no animation hook in Flutter 3.44)
- Simplified `ChatTabs` from `StatefulWidget` to `StatelessWidget`
- Focus-current-channel fade bump to 0.55; section-header alpha lifted to match the muted-label tier
- `addTab` now calls `setActiveTab` to snapshot outgoing tab's `lastSeenMessageId` — fixes spurious unread dots after adding a tab
- `onActivateSourceTab` threaded into `ChatUserModal` so Reply in merged mode switches to the correct source tab's composer

## Bug fixes and hardening
- **Reverted the experimental iOS low-latency mode** (5s live-edge join + 1.05x catch-up): AVPlayer can't sustain <~18s on Twitch (declared `TARGETDURATION:6` paces playlist refreshes), and the offset starved the buffer into pause-on-launch. Default join distance restored.
- Fork (Android): **cap `BEHIND_LIVE_WINDOW` recovery** so a stream repeatedly falling off the live window can't silently re-prepare forever; emits `error` on exhaustion so the host recovery ladder takes over
- Guard all Android `setAutoPipMode` calls with `_autoPipAvailable` — prevents `PlatformException` on Android 8–11; check `_disposed` after `isAutoPipAvailable` await to prevent post-dispose auto-PiP re-enable
- Remove `_isInPipMode` guard from `_onPaused` so `_paused` tracks actual state, fixing PiP play/pause toggle getting stuck
- Tighten iOS cookie domain check to exact `twitch.tv` / `.twitch.tv` suffix
- Invalidate the stored web session token when Twitch rejects it with a 401 (profile card flips back to unlinked; future loads skip the doomed authenticated request), and re-extract the cookie on launch when logged in without a linked session
- Send `play_session_id` and `player_backend=mediaplayer` to Usher, matching the web client / streamlink
- Fork (iOS): restore program-date-time latency measurement (a prior rev measured distance to the manifest edge, reading ~0s and silently disabling high-latency recovery / chat-delay auto-sync); release platform views on dispose (per-stream view + AVPlayerViewController leak), track the observed AVPlayerItem for KVO removal (sibling-view crash), main-thread seek results, resolve superseded load futures
- Fork (Android): clean up method handlers orphaned by PiP-time view disposal (leaked audio-focus listeners), drop the live-offset re-anchoring seekTo on metadata updates (latency creep), restore pre-duck volume, respect user pause in the stall watchdog, resolve superseded load futures
- Deep review pass: expire the quality-switch flag so stall recovery isn't disabled for the session, cap latency-driven recovery (clock-skew loop), generation-guard the error overlay, two-strike offline confirmation, controller null-safety on quality switch
- Tighten `/me` local-echo match (no longer renders `/meow ...` as an action); clear pending send text on disconnect

## Web / docs
- Remove stale Cloudflare Images binding from `wrangler.jsonc` (covered by `images.unoptimized: true`)
- Correct `web/AGENTS.md` Cache Components claim (feature not enabled)
- Repo and agent config cleanup

## Test plan
- [x] `flutter analyze` — clean (frosty + plugin lib)
- [x] `flutter test` — 319/319 pass (adds `ChatLatencySync`, `StreamInfoPoller`, video timing invariants, `PlaybackAccessToken`, IRC tag parsing)
- [x] Android plugin Kotlin compiles against the bumped fork rev
- [ ] Native player plays live streams on iOS and Android
- [ ] Quality switching works and persists across channel reopens
- [ ] PiP enters/exits correctly; pause/resume toggle in PiP window works
- [ ] Audio-only mode does not crash on Android < API 31
- [ ] Sending under a long synced chat delay no longer shows a false "may not have been sent" error
- [ ] Long composer text reflows the message list (no input/message overlap)
- [ ] Multi-tab: adding a tab does not mark previous tab as unread
- [ ] Merged chat: Reply from user modal targets the correct tab's composer

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-06-13 17:06:24 -04:00

310 lines
9.9 KiB
Dart

import 'dart:io';
import 'package:flutter/material.dart';
/// Shared shadow for overlay controls and text on top of video content.
const kOverlayShadow = [
Shadow(
offset: Offset(0, 1),
blurRadius: 4,
color: Color.fromRGBO(0, 0, 0, 0.3),
),
];
/// App-specific semantic colors that extend Material's [ColorScheme].
///
/// Colors that map to Material 3 roles use [ColorScheme] directly:
/// - Links → [ColorScheme.primary]
/// - Mentions → [ColorScheme.error]
/// - First-time chatters → [ColorScheme.tertiary]
///
/// Access via `Theme.of(context).extension<FrostyColors>()!` or the
/// `context.frostyColors` convenience extension.
class FrostyColors extends ThemeExtension<FrostyColors> {
final Color highlightedMessage;
final Color emoteOnly;
final Color followersOnly;
final Color slowMode;
final Color subOnly;
final Color uniqueMode;
final Color overlayOnSurface;
const FrostyColors({
required this.highlightedMessage,
required this.emoteOnly,
required this.followersOnly,
required this.slowMode,
required this.subOnly,
required this.uniqueMode,
required this.overlayOnSurface,
});
static FrostyColors light({required ColorScheme colorScheme}) => FrostyColors(
highlightedMessage: colorScheme.primary,
emoteOnly: const Color(0xFFFFB74D),
followersOnly: const Color(0xFFF44336),
slowMode: const Color(0xFF2196F3),
subOnly: const Color(0xFF4CAF50),
uniqueMode: const Color(0xFFAB47BC),
overlayOnSurface: Colors.white,
);
static FrostyColors dark({required ColorScheme colorScheme}) => FrostyColors(
highlightedMessage: colorScheme.primary,
emoteOnly: const Color(0xFFFFCC80),
followersOnly: const Color(0xFFE57373),
slowMode: const Color(0xFF64B5F6),
subOnly: const Color(0xFF81C784),
uniqueMode: const Color(0xFFBA68C8),
overlayOnSurface: Colors.white,
);
@override
FrostyColors copyWith({
Color? highlightedMessage,
Color? emoteOnly,
Color? followersOnly,
Color? slowMode,
Color? subOnly,
Color? uniqueMode,
Color? overlayOnSurface,
}) {
return FrostyColors(
highlightedMessage: highlightedMessage ?? this.highlightedMessage,
emoteOnly: emoteOnly ?? this.emoteOnly,
followersOnly: followersOnly ?? this.followersOnly,
slowMode: slowMode ?? this.slowMode,
subOnly: subOnly ?? this.subOnly,
uniqueMode: uniqueMode ?? this.uniqueMode,
overlayOnSurface: overlayOnSurface ?? this.overlayOnSurface,
);
}
@override
FrostyColors lerp(FrostyColors? other, double t) {
if (other is! FrostyColors) return this;
return FrostyColors(
highlightedMessage: Color.lerp(highlightedMessage, other.highlightedMessage, t)!,
emoteOnly: Color.lerp(emoteOnly, other.emoteOnly, t)!,
followersOnly: Color.lerp(followersOnly, other.followersOnly, t)!,
slowMode: Color.lerp(slowMode, other.slowMode, t)!,
subOnly: Color.lerp(subOnly, other.subOnly, t)!,
uniqueMode: Color.lerp(uniqueMode, other.uniqueMode, t)!,
overlayOnSurface: Color.lerp(overlayOnSurface, other.overlayOnSurface, t)!,
);
}
}
class FrostyThemes {
final Color colorSchemeSeed;
const FrostyThemes({required this.colorSchemeSeed});
ThemeData get light => createBaseTheme(
colorScheme: ColorScheme.fromSeed(seedColor: colorSchemeSeed),
backgroundColor: const Color.fromRGBO(248, 248, 248, 1),
);
ThemeData get dark => createBaseTheme(
colorScheme: ColorScheme.fromSeed(
seedColor: colorSchemeSeed,
brightness: Brightness.dark,
),
backgroundColor: Colors.black,
);
ThemeData createBaseTheme({
required ColorScheme colorScheme,
Color? backgroundColor,
}) {
final borderColor = colorScheme.outlineVariant.withValues(alpha: 0.5);
const borderWidth = 0.5;
return ThemeData(
extensions: [
colorScheme.brightness == Brightness.dark
? FrostyColors.dark(colorScheme: colorScheme)
: FrostyColors.light(colorScheme: colorScheme),
],
colorScheme: colorScheme,
fontFamily: 'Inter',
splashFactory: Platform.isIOS ? NoSplash.splashFactory : null,
textSelectionTheme: TextSelectionThemeData(
cursorColor: colorScheme.primary,
selectionColor: colorScheme.primary.withValues(alpha: 0.3),
selectionHandleColor: colorScheme.primary,
),
scaffoldBackgroundColor: backgroundColor,
bottomSheetTheme: BottomSheetThemeData(
showDragHandle: true,
backgroundColor: backgroundColor,
surfaceTintColor: backgroundColor,
),
menuTheme: MenuThemeData(
style: MenuStyle(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(vertical: 2),
),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(12)),
side: BorderSide(color: borderColor),
),
),
),
),
menuButtonTheme: MenuButtonThemeData(
style: MenuItemButton.styleFrom(
visualDensity: VisualDensity.compact,
minimumSize: const Size(0, 40),
padding: const EdgeInsets.symmetric(horizontal: 12),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
dialogTheme: DialogThemeData(
backgroundColor: backgroundColor,
surfaceTintColor: backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(16)),
side: BorderSide(color: borderColor),
),
),
appBarTheme: AppBarTheme(
elevation: 0,
backgroundColor: backgroundColor,
surfaceTintColor: backgroundColor,
titleSpacing: 0,
),
inputDecorationTheme: InputDecorationTheme(
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
filled: true,
fillColor: colorScheme.surfaceContainerHighest.withValues(alpha: 0.6),
hintStyle: TextStyle(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.normal,
),
border: OutlineInputBorder(
borderRadius: const BorderRadius.all(Radius.circular(100)),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: const BorderRadius.all(Radius.circular(100)),
borderSide: BorderSide.none,
),
disabledBorder: OutlineInputBorder(
borderRadius: const BorderRadius.all(Radius.circular(100)),
borderSide: BorderSide.none,
),
focusedBorder: OutlineInputBorder(
borderRadius: const BorderRadius.all(Radius.circular(100)),
borderSide: BorderSide(
color: colorScheme.primary.withValues(alpha: 0.8),
width: 1.5,
),
),
),
listTileTheme: ListTileThemeData(
titleTextStyle: TextStyle(
color: colorScheme.onSurface,
fontSize: 15,
fontWeight: FontWeight.w500,
letterSpacing: -0.011,
height: 1.5,
),
subtitleTextStyle: TextStyle(
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7),
fontSize: 13,
height: 1.4,
),
leadingAndTrailingTextStyle: TextStyle(
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
),
),
navigationBarTheme: NavigationBarThemeData(
elevation: 0,
backgroundColor: backgroundColor,
height: 64,
labelBehavior: NavigationDestinationLabelBehavior.alwaysHide,
indicatorColor: Colors.transparent,
indicatorShape: const CircleBorder(),
overlayColor: const WidgetStatePropertyAll(Colors.transparent),
),
tabBarTheme: const TabBarThemeData(
dividerColor: Colors.transparent,
tabAlignment: TabAlignment.start,
),
tooltipTheme: TooltipThemeData(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
showDuration: const Duration(seconds: 2),
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: const BorderRadius.all(Radius.circular(12)),
border: Border.all(color: borderColor),
),
textStyle: TextStyle(color: colorScheme.onSurface),
),
snackBarTheme: SnackBarThemeData(
showCloseIcon: true,
backgroundColor: backgroundColor,
shape: RoundedRectangleBorder(
side: BorderSide(color: borderColor),
borderRadius: const BorderRadius.all(Radius.circular(12)),
),
behavior: SnackBarBehavior.floating,
),
dividerTheme: DividerThemeData(
thickness: borderWidth,
space: borderWidth,
color: borderColor,
),
textTheme: TextTheme(
// Alert dialog title
headlineSmall: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
letterSpacing: -0.019,
),
// App bar title
titleLarge: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
letterSpacing: -0.019,
),
// Section titles
titleMedium: TextStyle(
fontWeight: FontWeight.w600,
letterSpacing: -0.011,
),
// Tab bar title
titleSmall: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
letterSpacing: -0.011,
),
// Labels
labelLarge: TextStyle(
fontWeight: FontWeight.w500,
letterSpacing: -0.006,
),
labelMedium: TextStyle(fontWeight: FontWeight.w500, letterSpacing: 0),
labelSmall: TextStyle(
fontWeight: FontWeight.w500,
letterSpacing: 0.005,
),
// Body text
bodyLarge: TextStyle(
fontWeight: FontWeight.w500,
letterSpacing: -0.011,
),
bodyMedium: TextStyle(letterSpacing: -0.006),
bodySmall: TextStyle(letterSpacing: 0),
),
);
}
}