From 3f6a4561b95e1a6dca211a169e83d4c795ba57aa Mon Sep 17 00:00:00 2001 From: Wouter van Wijk Date: Fri, 13 Nov 2026 11:24:37 +0100 Subject: [PATCH 1/2] fix useragent --- lib/services/collectors/server_fetcher.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/services/collectors/server_fetcher.dart b/lib/services/collectors/server_fetcher.dart index 9d422a5..5765dd1 100644 --- a/lib/services/collectors/server_fetcher.dart +++ b/lib/services/collectors/server_fetcher.dart @@ -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 { From 2524f7bd9dc5c543e5b68ac915e32ccf7f4161bd Mon Sep 17 00:00:00 2001 From: Wouter van Wijk Date: Fri, 13 Nov 2026 11:27:21 +0100 Subject: [PATCH 2/2] Add Low resource mode setting for older devices The Browser and Reader tabs each keep their own InAppWebView alive (KeepAliveWrapper in the TabBarView), so on memory/CPU-constrained devices two web renderer processes run at once. The new opt-in setting (Settings > Behavior > Low resource mode, off by default) pauses the WebView of a hidden tab (WebView.onPause / WebView2 TrySuspend, media paused everywhere) and resumes it when its tab is selected, requires a user tap before media plays in the Browser tab, sets Android rendererPriorityPolicy waivedWhenNotVisible so hidden pages can be reclaimed under memory pressure, and suspends both WebViews while the app is backgrounded. Reader extraction still runs against the live browser view before it is paused. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 1 + lib/main.dart | 4 ++ lib/models/settings.dart | 18 ++++++ lib/screens/settings_screen.dart | 11 ++++ lib/services/html_service.dart | 91 ++++++++++++++++++++++++++++- lib/utils/low_resource_webview.dart | 16 +++++ lib/widgets/browser_view.dart | 25 +++++--- lib/widgets/reader_view.dart | 21 ++++++- test/low_resource_mode_test.dart | 23 ++++++++ 9 files changed, 196 insertions(+), 14 deletions(-) create mode 100644 lib/utils/low_resource_webview.dart create mode 100644 test/low_resource_mode_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index f117c3e..1f506be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/lib/main.dart b/lib/main.dart index a86ab86..765649c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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(); } } } diff --git a/lib/models/settings.dart b/lib/models/settings.dart index 8c8aa47..c14bd49 100644 --- a/lib/models/settings.dart +++ b/lib/models/settings.dart @@ -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; @@ -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 _siteJurisdictions = {}; // domain -> jurisdiction @@ -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; @@ -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]; @@ -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 { @@ -404,6 +420,7 @@ class AppSettings with ChangeNotifier { _scrollToLoadLazy = false; _disableBrowserCache = false; _cleanCookies = false; + _lowResourceMode = false; // Save the default values _saveAllSettings(); @@ -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 diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index a13efe3..7413f88 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -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, diff --git a/lib/services/html_service.dart b/lib/services/html_service.dart index 58ceaf2..eaef326 100644 --- a/lib/services/html_service.dart +++ b/lib/services/html_service.dart @@ -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 _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 _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 triggerBrowserReload() async { final controller = activeWebViewController; @@ -2315,7 +2386,7 @@ Technical details: $message'''; _verticalScrollController = null; _activeHorizontalScrollController = null; - _appSettings?.removeListener(notifyListeners); + _appSettings?.removeListener(_onAppSettingsChanged); super.dispose(); } @@ -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) { diff --git a/lib/utils/low_resource_webview.dart b/lib/utils/low_resource_webview.dart new file mode 100644 index 0000000..cae69d9 --- /dev/null +++ b/lib/utils/low_resource_webview.dart @@ -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, + ); +} diff --git a/lib/widgets/browser_view.dart b/lib/widgets/browser_view.dart index 14319c4..ccfe6ec 100644 --- a/lib/widgets/browser_view.dart +++ b/lib/widgets/browser_view.dart @@ -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'; @@ -49,11 +50,11 @@ class _BrowserViewState extends State { _htmlService = Provider.of(context, listen: false); final s = Provider.of(context, listen: false); if (!identical(_appSettings, s)) { - _appSettings?.removeListener(_applyCacheSetting); + _appSettings?.removeListener(_applyWebViewSettings); _appSettings = s; - _appSettings?.addListener(_applyCacheSetting); + _appSettings?.addListener(_applyWebViewSettings); } - _applyCacheSetting(); + _applyWebViewSettings(); } @override @@ -65,13 +66,14 @@ class _BrowserViewState extends State { 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; @@ -82,6 +84,8 @@ class _BrowserViewState extends State { cacheMode: s.disableBrowserCache ? CacheMode.LOAD_NO_CACHE : CacheMode.LOAD_DEFAULT, + mediaPlaybackRequiresUserGesture: s.lowResourceMode, + rendererPriorityPolicy: lowResourceRendererPriorityPolicy(s), )) .ignore(); } @@ -221,7 +225,9 @@ class _BrowserViewState extends State { @override Widget build(BuildContext context) { - final disableCache = context.watch().disableBrowserCache; + final appSettings = context.watch(); + final disableCache = appSettings.disableBrowserCache; + final lowResource = appSettings.lowResourceMode; final webView = InAppWebView( gestureRecognizers: widget.gestureRecognizers, onWebContentProcessDidTerminate: (controller) { @@ -232,7 +238,9 @@ class _BrowserViewState extends State { 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, @@ -242,6 +250,7 @@ class _BrowserViewState extends State { cacheEnabled: !disableCache, cacheMode: disableCache ? CacheMode.LOAD_NO_CACHE : CacheMode.LOAD_DEFAULT, + rendererPriorityPolicy: lowResourceRendererPriorityPolicy(appSettings), ), initialUserScripts: UnmodifiableListView([ // Resource observer + fetch/XHR patch, and the one-shot collector diff --git a/lib/widgets/reader_view.dart b/lib/widgets/reader_view.dart index 93bb6b0..057a7be 100644 --- a/lib/widgets/reader_view.dart +++ b/lib/widgets/reader_view.dart @@ -7,6 +7,7 @@ import 'package:view_source_vibe/models/settings.dart'; import 'package:view_source_vibe/services/collectors/readability_js.dart'; import 'package:view_source_vibe/services/html_service.dart'; import 'package:view_source_vibe/services/reader_service.dart'; +import 'package:view_source_vibe/utils/low_resource_webview.dart'; /// The Reader tab: the current page rendered as a clean article, extracted /// with Readability.js (see [ReaderService]). All parsing happens in the @@ -23,6 +24,7 @@ class ReaderView extends StatefulWidget { class _ReaderViewState extends State { ReaderService? _reader; + AppSettings? _appSettings; bool _inViewParsed = false; @override @@ -30,6 +32,8 @@ class _ReaderViewState extends State { super.initState(); _reader = context.read(); _reader!.addListener(_onReader); + _appSettings = context.read(); + _appSettings!.addListener(_onAppSettings); // Sync after the first frame so notifyListeners never fires mid-build. WidgetsBinding.instance.addPostFrameCallback((_) => _syncWithService()); } @@ -37,10 +41,19 @@ class _ReaderViewState extends State { @override void dispose() { _reader?.removeListener(_onReader); + _appSettings?.removeListener(_onAppSettings); _reader?.setViewController(null); super.dispose(); } + /// Applies live-adjustable settings (low-resource renderer policy) to the + /// running reader WebView when the setting changes. + void _onAppSettings() { + final s = _appSettings; + if (s == null) return; + _reader?.viewController?.setSettings(settings: _buildSettings(s)).ignore(); + } + void _onReader() => _syncWithService(); /// Kicks off extraction when the article is missing or outdated. Rendering @@ -76,13 +89,14 @@ class _ReaderViewState extends State { } } - InAppWebViewSettings get _settings => InAppWebViewSettings( + InAppWebViewSettings _buildSettings(AppSettings s) => InAppWebViewSettings( isInspectable: kDebugMode, mediaPlaybackRequiresUserGesture: true, allowFileAccess: false, allowFileAccessFromFileURLs: false, allowContentAccess: false, allowsInlineMediaPlayback: true, + rendererPriorityPolicy: lowResourceRendererPriorityPolicy(s), ); void _onWebViewCreated(InAppWebViewController controller) { @@ -120,6 +134,7 @@ class _ReaderViewState extends State { @override Widget build(BuildContext context) { final reader = context.watch(); + final appSettings = context.watch(); // Watch the effective dark mode so a theme change re-renders the article. return Selector( selector: (context, s) => s.themeMode == ThemeModeOption.system @@ -162,7 +177,7 @@ class _ReaderViewState extends State { return InAppWebView( key: ValueKey('reader-article-${html.hashCode}'), gestureRecognizers: widget.gestureRecognizers, - initialSettings: _settings, + initialSettings: _buildSettings(appSettings), initialData: InAppWebViewInitialData( data: html, baseUrl: base != null && base.isNotEmpty ? WebUri(base) : null, @@ -183,7 +198,7 @@ class _ReaderViewState extends State { return InAppWebView( key: ValueKey('reader-raw-$path'), gestureRecognizers: widget.gestureRecognizers, - initialSettings: _settings, + initialSettings: _buildSettings(appSettings), initialData: content.isNotEmpty ? InAppWebViewInitialData(data: content, baseUrl: base) : null, diff --git a/test/low_resource_mode_test.dart b/test/low_resource_mode_test.dart new file mode 100644 index 0000000..16f80bf --- /dev/null +++ b/test/low_resource_mode_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:view_source_vibe/models/settings.dart'; + +void main() { + test('low resource mode is off by default, persists, and resets', () async { + SharedPreferences.setMockInitialValues({}); + final settings = AppSettings(); + await settings.initialize(); + expect(settings.lowResourceMode, isFalse); + + settings.lowResourceMode = true; + expect(settings.lowResourceMode, isTrue); + + // Survives a restart. + final reloaded = AppSettings(); + await reloaded.initialize(); + expect(reloaded.lowResourceMode, isTrue); + + reloaded.resetToDefaults(); + expect(reloaded.lowResourceMode, isFalse); + }); +}