Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ All notable, user-facing changes to View Source Vibe are documented here.
- **Reader** tab (HTML pages): renders the page as a clean article using Readability.js, extracted from the live browser view when available. Links in the article open in the Browser tab.
- **Size** tab: "Fresh load" measurement — reloads the page with an empty cache on a phone-sized viewport and shows both loads side by side, each with its own verdict. Third-party iframes are labelled.
- Settings → Behavior: **Load lazy content** (off by default) scrolls the page once after it loads — and back to the top — so lazy images and embeds are actually fetched and measured; a banner above the Browser tab shows while this happens. Plus **Disable browser cache** and **Always clean cookies**.
- Settings → Behavior: **Low resource mode** (off by default) for older devices. The Browser and Reader tabs each run their own WebView, and both stay alive at once; in this mode the WebView of a hidden tab is paused (and its media stopped) until its tab is selected again, media in the Browser tab only plays after a tap, Android marks hidden pages as waived renderer priority so the system can reclaim their memory, and both WebViews are suspended while the app is in the background.

### Improved
- Central data point: one reactive store per page load holding the browser, server and file results (with a generation, so stale results are dropped).
Expand Down
4 changes: 4 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,10 @@ class AppLifecycleObserver with WidgetsBindingObserver {
// App is going to background or being closed - save state
debugPrint('📱 App going to background, saving state...');
htmlService.saveCurrentState(appStateService);
// Low-resource mode: suspend both WebViews while backgrounded.
htmlService.suspendWebViewsForBackground();
} else if (state == AppLifecycleState.resumed) {
htmlService.resumeWebViews();
}
}
}
18 changes: 18 additions & 0 deletions lib/models/settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class AppSettings with ChangeNotifier {
static const String _prefsScrollToLoadLazy = 'scrollToLoadLazy';
static const String _prefsDisableBrowserCache = 'disableBrowserCache';
static const String _prefsCleanCookies = 'cleanCookies';
static const String _prefsLowResourceMode = 'lowResourceMode';
static const String _prefsHomeJurisdiction = 'homeJurisdiction';
static const String _prefsSiteJurisdictions = 'siteJurisdictions';
static const int _maxSiteJurisdictions = 255;
Expand All @@ -53,6 +54,7 @@ class AppSettings with ChangeNotifier {
bool _scrollToLoadLazy = false;
bool _disableBrowserCache = false;
bool _cleanCookies = false;
bool _lowResourceMode = false;
String? _homeJurisdiction; // null = from device locale
Map<String, String> _siteJurisdictions = {}; // domain -> jurisdiction

Expand All @@ -75,6 +77,11 @@ class AppSettings with ChangeNotifier {
/// Clear all cookies before every page load: each visit starts cookieless.
bool get cleanCookies => _cleanCookies;

/// For older devices: pause the Browser/Reader WebView while its tab is
/// hidden, require a tap before media plays, and let the system reclaim
/// memory from hidden pages.
bool get lowResourceMode => _lowResourceMode;

/// Fallback jurisdiction for sites whose legal home isn't detected;
/// null = from the device locale.
String? get homeJurisdictionSetting => _homeJurisdiction;
Expand Down Expand Up @@ -314,6 +321,14 @@ class AppSettings with ChangeNotifier {
}
}

set lowResourceMode(bool value) {
if (_lowResourceMode != value) {
_lowResourceMode = value;
_saveSetting(_prefsLowResourceMode, value);
notifyListeners();
}
}

/// Manually chosen legal home for a site (by registrable domain).
String? siteJurisdiction(String domain) => _siteJurisdictions[domain];

Expand Down Expand Up @@ -365,6 +380,7 @@ class AppSettings with ChangeNotifier {
_scrollToLoadLazy = _prefs!.getBool(_prefsScrollToLoadLazy) ?? false;
_disableBrowserCache = _prefs!.getBool(_prefsDisableBrowserCache) ?? false;
_cleanCookies = _prefs!.getBool(_prefsCleanCookies) ?? false;
_lowResourceMode = _prefs!.getBool(_prefsLowResourceMode) ?? false;
final home = _prefs!.getString(_prefsHomeJurisdiction);
_homeJurisdiction = (home == null || home.isEmpty) ? null : home;
try {
Expand Down Expand Up @@ -404,6 +420,7 @@ class AppSettings with ChangeNotifier {
_scrollToLoadLazy = false;
_disableBrowserCache = false;
_cleanCookies = false;
_lowResourceMode = false;

// Save the default values
_saveAllSettings();
Expand All @@ -424,6 +441,7 @@ class AppSettings with ChangeNotifier {
await _saveSetting(_prefsScrollToLoadLazy, _scrollToLoadLazy);
await _saveSetting(_prefsDisableBrowserCache, _disableBrowserCache);
await _saveSetting(_prefsCleanCookies, _cleanCookies);
await _saveSetting(_prefsLowResourceMode, _lowResourceMode);
}

// Theme categories and metadata
Expand Down
11 changes: 11 additions & 0 deletions lib/screens/settings_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,17 @@ class SettingsScreen extends StatelessWidget {
onChanged: (value) => settings.cleanCookies = value,
),
),
_settingsTile(
context: context,
icon: Icons.battery_saver_outlined,
title: 'Low resource mode',
description:
'For older devices: pause the Browser/Reader WebView while its tab is hidden, require a tap before media plays, and let the system reclaim memory from hidden pages',
control: Switch(
value: settings.lowResourceMode,
onChanged: (value) => settings.lowResourceMode = value,
),
),
_settingsTile(
context: context,
icon: Icons.gavel_outlined,
Expand Down
2 changes: 1 addition & 1 deletion lib/services/collectors/server_fetcher.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import '../probe_service.dart';

/// The User-Agent of every direct fetch: honest about being this app.
const kServerUserAgent =
'ViewSourceVibe/1.2 (+https://github.com/woutervanwijk/viewsourcevibe)';
'ViewSourceVibe/1.3.0 (+https://github.com/woutervanwijk/viewsourcevibe)';

/// Curl-like direct fetch of a URL, independent of any WebView.
abstract class ServerFetcher {
Expand Down
91 changes: 88 additions & 3 deletions lib/services/html_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1481,11 +1481,82 @@ class HtmlService extends ChangeNotifier {

// Reader tab: extract the article lazily, once per page generation.
if (isHtml && index == readerTabIndex) {
_readerService?.extractIfStale().ignore();
final reader = _readerService;
if (reader != null) {
// In low-resource mode the Browser WebView is paused once its tab
// is hidden, but extraction evaluates JS in it — so pause only
// after the extraction has finished.
reader.extractIfStale().whenComplete(_applyWebViewResourceMode).ignore();
} else {
_applyWebViewResourceMode();
}
} else {
_applyWebViewResourceMode();
}
}
}

/// In low-resource mode, pause the WebView whose tab is not visible
/// (Android `WebView.onPause` / Windows `TrySuspend`) and pause its media,
/// so the Browser and Reader WebViews don't both burn CPU/memory on older
/// devices. The visible tab's WebView is resumed. No-op when the setting
/// is off.
void _applyWebViewResourceMode() {
if (!(_appSettings?.lowResourceMode ?? false)) return;
final browserActive = _activeTabIndex == browserTabIndex;
final readerActive = isHtml && _activeTabIndex == readerTabIndex;
_setWebViewPaused(activeWebViewController, paused: !browserActive);
final readerController = _readerService?.viewController;
if (readerController != null &&
!identical(readerController, activeWebViewController)) {
_setWebViewPaused(readerController, paused: !readerActive);
}
}

Future<void> _setWebViewPaused(InAppWebViewController? controller,
{required bool paused}) async {
if (controller == null) return;
try {
if (paused) {
await controller.pause();
await _pauseWebViewMedia(controller);
} else {
await controller.resume();
}
} catch (e) {
// pause()/resume() are only implemented on Android and Windows; the
// other platforms suspend background WebViews themselves.
debugPrint('WebView pause/resume not supported on this platform: $e');
}
}

Future<void> _pauseWebViewMedia(InAppWebViewController controller) async {
try {
await controller.pauseAllMediaPlayback();
} catch (_) {
// Android has no native pauseAllMediaPlayback; pause via JS instead.
try {
await controller.evaluateJavascript(
source: "document.querySelectorAll('video,audio')"
'.forEach(function(m){try{m.pause()}catch(e){}});');
} catch (_) {}
}
}

/// App went to background: suspend both WebViews (low-resource mode only).
void suspendWebViewsForBackground() {
if (!(_appSettings?.lowResourceMode ?? false)) return;
_setWebViewPaused(activeWebViewController, paused: true);
_setWebViewPaused(_readerService?.viewController, paused: true);
}

/// App is back in the foreground: resume the WebViews. Safe to call even
/// when low-resource mode is off (nothing was paused then).
void resumeWebViews() {
_setWebViewPaused(activeWebViewController, paused: false);
_setWebViewPaused(_readerService?.viewController, paused: false);
}

/// Trigger a browser reload if the URL has changed and the browser tab is visible
Future<void> triggerBrowserReload() async {
final controller = activeWebViewController;
Expand Down Expand Up @@ -2315,7 +2386,7 @@ Technical details: $message''';
_verticalScrollController = null;
_activeHorizontalScrollController = null;

_appSettings?.removeListener(notifyListeners);
_appSettings?.removeListener(_onAppSettingsChanged);

super.dispose();
}
Expand Down Expand Up @@ -2379,7 +2450,21 @@ Technical details: $message''';
void setAppSettings(AppSettings settings) {
_appSettings = settings;
// Listen to settings changes to update tab indices dynamically
_appSettings?.addListener(notifyListeners);
_appSettings?.addListener(_onAppSettingsChanged);
}

bool _lowResourceModeWasOn = false;

void _onAppSettingsChanged() {
final low = _appSettings?.lowResourceMode ?? false;
if (low) {
_applyWebViewResourceMode();
} else if (_lowResourceModeWasOn) {
// Turned off: make sure no WebView stays paused.
resumeWebViews();
}
_lowResourceModeWasOn = low;
notifyListeners();
}

void setUrlHistoryService(UrlHistoryService service) {
Expand Down
16 changes: 16 additions & 0 deletions lib/utils/low_resource_webview.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'dart:io';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:view_source_vibe/models/settings.dart';

/// Android renderer priority policy for low-resource mode: keep the page's
/// renderer at normal priority while the WebView is visible, but let the
/// system treat it as waived (a prime target for memory reclaim) while the
/// tab is hidden. Null when low-resource mode is off or not on Android.
RendererPriorityPolicy? lowResourceRendererPriorityPolicy(AppSettings s) {
if (!s.lowResourceMode || !Platform.isAndroid) return null;
return RendererPriorityPolicy(
rendererRequestedPriority: RendererPriority.RENDERER_PRIORITY_IMPORTANT,
waivedWhenNotVisible: true,
);
}
25 changes: 17 additions & 8 deletions lib/widgets/browser_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'package:view_source_vibe/services/collectors/vsv_collect_js.dart';
import 'package:view_source_vibe/services/html_service.dart';
import 'package:view_source_vibe/services/navigation_policy.dart';
import 'package:view_source_vibe/services/rss_template_service.dart';
import 'package:view_source_vibe/utils/low_resource_webview.dart';
import 'package:view_source_vibe/widgets/scroll_through_banner.dart';
import 'dart:io';
import 'dart:collection';
Expand Down Expand Up @@ -49,11 +50,11 @@ class _BrowserViewState extends State<BrowserView> {
_htmlService = Provider.of<HtmlService>(context, listen: false);
final s = Provider.of<AppSettings>(context, listen: false);
if (!identical(_appSettings, s)) {
_appSettings?.removeListener(_applyCacheSetting);
_appSettings?.removeListener(_applyWebViewSettings);
_appSettings = s;
_appSettings?.addListener(_applyCacheSetting);
_appSettings?.addListener(_applyWebViewSettings);
}
_applyCacheSetting();
_applyWebViewSettings();
}

@override
Expand All @@ -65,13 +66,14 @@ class _BrowserViewState extends State<BrowserView> {
void dispose() {
// Use the cached reference — Provider.of is NOT safe here
// because the widget's element is already deactivated.
_appSettings?.removeListener(_applyCacheSetting);
_appSettings?.removeListener(_applyWebViewSettings);
_htmlService?.clearWebViewController();
super.dispose();
}

/// Applies the "Disable browser cache" setting to the live WebView.
void _applyCacheSetting() {
/// Applies the live-adjustable WebView settings ("Disable browser cache",
/// low-resource media/renderer policy) to the running WebView.
void _applyWebViewSettings() {
final s = _appSettings;
final c = _controller;
if (s == null || c == null) return;
Expand All @@ -82,6 +84,8 @@ class _BrowserViewState extends State<BrowserView> {
cacheMode: s.disableBrowserCache
? CacheMode.LOAD_NO_CACHE
: CacheMode.LOAD_DEFAULT,
mediaPlaybackRequiresUserGesture: s.lowResourceMode,
rendererPriorityPolicy: lowResourceRendererPriorityPolicy(s),
))
.ignore();
}
Expand Down Expand Up @@ -221,7 +225,9 @@ class _BrowserViewState extends State<BrowserView> {

@override
Widget build(BuildContext context) {
final disableCache = context.watch<AppSettings>().disableBrowserCache;
final appSettings = context.watch<AppSettings>();
final disableCache = appSettings.disableBrowserCache;
final lowResource = appSettings.lowResourceMode;
final webView = InAppWebView(
gestureRecognizers: widget.gestureRecognizers,
onWebContentProcessDidTerminate: (controller) {
Expand All @@ -232,7 +238,9 @@ class _BrowserViewState extends State<BrowserView> {
initialSettings: InAppWebViewSettings(
isInspectable: kDebugMode,
preferredContentMode: UserPreferredContentMode.RECOMMENDED,
mediaPlaybackRequiresUserGesture: false,
// Low-resource mode: no autoplay — media only plays after a tap, so
// hidden tabs don't burn CPU on video decoding.
mediaPlaybackRequiresUserGesture: lowResource,
allowFileAccess: false,
allowFileAccessFromFileURLs: false,
allowContentAccess: false,
Expand All @@ -242,6 +250,7 @@ class _BrowserViewState extends State<BrowserView> {
cacheEnabled: !disableCache,
cacheMode:
disableCache ? CacheMode.LOAD_NO_CACHE : CacheMode.LOAD_DEFAULT,
rendererPriorityPolicy: lowResourceRendererPriorityPolicy(appSettings),
),
initialUserScripts: UnmodifiableListView<UserScript>([
// Resource observer + fetch/XHR patch, and the one-shot collector
Expand Down
Loading
Loading