Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Share and improve log file viewer

Neeraj Gupta8273009686ca
diff --git a/mobile/apps/auth/lib/ui/tools/debug/log_file_viewer.dart b/mobile/apps/auth/lib/ui/tools/debug/log_file_viewer.dart
deleted file mode 100644
index d3bc93742b..0000000000
--- a/mobile/apps/auth/lib/ui/tools/debug/log_file_viewer.dart
+++ /dev/null
@@ -1,57 +0,0 @@
-import 'dart:io';
-
-import 'package:ente_auth/utils/platform_util.dart';
-import 'package:ente_strings/ente_strings.dart';
-import 'package:ente_ui/components/loading_widget.dart';
-import 'package:flutter/material.dart';
-
-class LogFileViewer extends StatefulWidget {
- final File file;
- const LogFileViewer(this.file, {super.key});
-
- @override
- State<LogFileViewer> createState() => _LogFileViewerState();
-}
-
-class _LogFileViewerState extends State<LogFileViewer> {
- String? _logs;
- @override
- void initState() {
- widget.file.readAsString().then((logs) {
- setState(() {
- _logs = logs;
- });
- });
- super.initState();
- }
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(elevation: 0, title: Text(context.strings.todaysLogs)),
- body: _getBody(),
- );
- }
-
- Widget _getBody() {
- if (_logs == null) {
- return const EnteLoadingWidget();
- }
- return Container(
- padding: const EdgeInsets.only(left: 12, top: 8, right: 12),
- child: SingleChildScrollView(
- child: SelectableRegion(
- focusNode: FocusNode(),
- selectionControls: PlatformUtil.selectionControls,
- child: Text(
- _logs!,
- style: const TextStyle(
- fontFeatures: [FontFeature.tabularFigures()],
- height: 1.2,
- ),
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/utils/email_util.dart b/mobile/apps/auth/lib/utils/email_util.dart
index 34ca014d8c..b019d2c120 100644
--- a/mobile/apps/auth/lib/utils/email_util.dart
+++ b/mobile/apps/auth/lib/utils/email_util.dart
@@ -4,7 +4,6 @@ import 'package:archive/archive_io.dart';
import 'package:email_validator/email_validator.dart';
import 'package:ente_auth/core/configuration.dart';
import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/tools/debug/log_file_viewer.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/directory_utils.dart' as auth_dir;
import 'package:ente_auth/utils/share_utils.dart' as auth_share;
@@ -13,6 +12,7 @@ import 'package:ente_logging/logging.dart';
import 'package:ente_strings/ente_strings.dart';
import 'package:ente_ui/components/buttons/button_widget.dart';
import 'package:ente_ui/components/buttons/models/button_type.dart';
+import 'package:ente_ui/pages/log_file_viewer.dart';
import 'package:ente_utils/ente_utils.dart';
import 'package:file_saver/file_saver.dart';
import 'package:flutter/material.dart';
@@ -59,20 +59,15 @@ Future<void> sendLogs(
}
},
),
- //isInAlert is false here as we don't want to the dialog to dismiss
- //on pressing this button
ButtonWidget(
buttonType: ButtonType.secondary,
labelText: l10n.viewLogsAction,
buttonAction: ButtonAction.second,
onTap: () async {
- await showDialog(
- context: context,
- builder: (BuildContext context) {
- return LogFileViewer(SuperLogging.logFile!);
- },
- barrierColor: Colors.black87,
- barrierDismissible: false,
+ await Navigator.of(context).push(
+ MaterialPageRoute(
+ builder: (_) => LogFileViewer(SuperLogging.logFile!),
+ ),
);
},
),
diff --git a/mobile/apps/photos/lib/ui/settings/support/help_support_page.dart b/mobile/apps/photos/lib/ui/settings/support/help_support_page.dart
index 7fbd31bcc9..9d6ad855bc 100644
--- a/mobile/apps/photos/lib/ui/settings/support/help_support_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/support/help_support_page.dart
@@ -1,5 +1,6 @@
import "package:ente_components/ente_components.dart";
import "package:ente_strings/ente_strings.dart";
+import "package:ente_ui/pages/log_file_viewer.dart";
import "package:flutter/foundation.dart";
import "package:flutter/material.dart";
import "package:hugeicons/hugeicons.dart";
@@ -10,7 +11,6 @@ import "package:photos/service_locator.dart";
import "package:photos/ui/common/web_page.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/ui/settings/support/report_issue_page.dart";
-import "package:photos/ui/tools/debug/log_file_viewer.dart";
import "package:photos/utils/email_util.dart";
import "package:url_launcher/url_launcher_string.dart";
diff --git a/mobile/apps/photos/lib/ui/tools/debug/log_file_viewer.dart b/mobile/apps/photos/lib/ui/tools/debug/log_file_viewer.dart
deleted file mode 100644
index 532afa6117..0000000000
--- a/mobile/apps/photos/lib/ui/tools/debug/log_file_viewer.dart
+++ /dev/null
@@ -1,70 +0,0 @@
-import "dart:io";
-
-import "package:ente_strings/ente_strings.dart";
-import "package:ente_ui/components/loading_widget.dart";
-import "package:flutter/material.dart";
-
-class LogFileViewer extends StatefulWidget {
- final File file;
- const LogFileViewer(this.file, {super.key});
-
- @override
- State<LogFileViewer> createState() => _LogFileViewerState();
-}
-
-class _LogFileViewerState extends State<LogFileViewer> {
- static const _maxLinesToShow = 2000;
-
- late final Future<List<String>> _logsFuture;
-
- @override
- void initState() {
- super.initState();
- _logsFuture = _readLogs();
- }
-
- Future<List<String>> _readLogs() async {
- final logs = await widget.file.readAsLines();
- if (logs.length <= _maxLinesToShow) {
- return logs;
- }
- return logs.sublist(logs.length - _maxLinesToShow);
- }
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(elevation: 0, title: Text(context.strings.todaysLogs)),
- body: FutureBuilder<List<String>>(
- future: _logsFuture,
- builder: (context, snapshot) {
- if (snapshot.hasError) {
- return Center(child: Text(snapshot.error.toString()));
- }
- if (!snapshot.hasData) {
- return const EnteLoadingWidget();
- }
- final logs = snapshot.data!;
- return Scrollbar(
- interactive: true,
- thickness: 4,
- radius: const Radius.circular(2),
- child: ListView.builder(
- padding: const EdgeInsets.only(left: 12, top: 8, right: 12),
- itemCount: logs.length,
- itemBuilder: (context, index) {
- return Text(
- logs[index],
- style: const TextStyle(
- fontFeatures: [FontFeature.tabularFigures()],
- height: 1.2,
- ),
- );
- },
- ),
- );
- },
- ),
- );
- }
-}
diff --git a/mobile/apps/photos/lib/utils/email_util.dart b/mobile/apps/photos/lib/utils/email_util.dart
index eb91975a5f..3fdb358434 100644
--- a/mobile/apps/photos/lib/utils/email_util.dart
+++ b/mobile/apps/photos/lib/utils/email_util.dart
@@ -4,6 +4,7 @@ import 'package:archive/archive_io.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:email_validator/email_validator.dart';
import "package:ente_strings/ente_strings.dart";
+import 'package:ente_ui/pages/log_file_viewer.dart';
import "package:file_saver/file_saver.dart";
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -24,7 +25,6 @@ import 'package:photos/ui/components/buttons/button_widget_v2.dart';
import 'package:photos/ui/components/dialog_widget.dart';
import 'package:photos/ui/components/models/button_type.dart';
import 'package:photos/ui/notification/toast.dart';
-import 'package:photos/ui/tools/debug/log_file_viewer.dart';
import 'package:photos/utils/dialog_util.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -66,22 +66,15 @@ Future<void> sendLogs(
}
},
),
- //isInAlert is false here as we don't want to the dialog to dismiss
- //on pressing this button
ButtonWidget(
buttonType: ButtonType.secondary,
labelText: context.strings.viewLogs,
buttonAction: ButtonAction.second,
onTap: () async {
- // ignore: unawaited_futures
- showDialog(
- useRootNavigator: false,
- context: context,
- builder: (BuildContext context) {
- return LogFileViewer(SuperLogging.logFile!);
- },
- barrierColor: Colors.black87,
- barrierDismissible: false,
+ await Navigator.of(context).push(
+ MaterialPageRoute(
+ builder: (_) => LogFileViewer(SuperLogging.logFile!),
+ ),
);
},
),
diff --git a/mobile/packages/logging/lib/log_file_reader.dart b/mobile/packages/logging/lib/log_file_reader.dart
new file mode 100644
index 0000000000..9c6ce493e5
--- /dev/null
+++ b/mobile/packages/logging/lib/log_file_reader.dart
@@ -0,0 +1,108 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+import 'dart:typed_data';
+
+final _logRecordHeader = RegExp(
+ r'^[ \t]*(?:\[[^\]]+\][ \t]+)?\[([^\]]+)\][ \t]*\[[A-Z]+\][ \t]+\[([0-9]{4}-[^\]]+)\][ \t]*(.*)',
+);
+
+class LogFileEntry {
+ LogFileEntry._(this.text) : _header = _logRecordHeader.firstMatch(text);
+
+ final RegExpMatch? _header;
+ final String text;
+
+ String? get loggerName => _header?.group(1);
+ DateTime? get timestamp => DateTime.tryParse(_header?.group(2) ?? '');
+ String? get message => _header?.group(3);
+}
+
+class LogFileReader {
+ LogFileReader(this._file);
+
+ static const _pageLineCount = 2000;
+ static const _readChunkSize = 64 * 1024;
+
+ final File _file;
+ String? _continuedEntry;
+ int _position = 0;
+
+ bool get hasMore => _position > 0;
+
+ Future<void> reset() async {
+ _position = await _file.length();
+ _continuedEntry = null;
+ }
+
+ Future<List<LogFileEntry>> readPreviousPage() async {
+ final result = <LogFileEntry>[];
+ while (result.isEmpty && hasMore) {
+ final page = await _readPage(_position);
+ _position = page.start;
+ final entries = page.entries;
+ if (entries.isEmpty) continue;
+
+ final continuedEntry = _continuedEntry;
+ if (continuedEntry != null) {
+ entries.last = '${entries.last}\n$continuedEntry';
+ _continuedEntry = null;
+ }
+ if (hasMore && page.firstEntryContinuesPrevious) {
+ _continuedEntry = entries.removeAt(0);
+ }
+ result.addAll(entries.reversed.map(LogFileEntry._));
+ }
+ return result;
+ }
+
+ Future<({int start, List<String> entries, bool firstEntryContinuesPrevious})>
+ _readPage(int end) async {
+ final handle = await _file.open();
+ try {
+ var position = end;
+ var newlineCount = 0;
+ final chunks = <Uint8List>[];
+
+ while (position > 0 && newlineCount <= _pageLineCount) {
+ final length = min(_readChunkSize, position);
+ position -= length;
+ await handle.setPosition(position);
+ final chunk = await handle.read(length);
+ chunks.add(chunk);
+ for (final byte in chunk) {
+ if (byte == 10) newlineCount++;
+ }
+ }
+
+ final bytes = BytesBuilder(copy: false);
+ for (final chunk in chunks.reversed) {
+ bytes.add(chunk);
+ }
+ var pageBytes = bytes.takeBytes();
+ if (position > 0) {
+ final firstNewline = pageBytes.indexOf(10);
+ position += firstNewline + 1;
+ pageBytes = Uint8List.sublistView(pageBytes, firstNewline + 1);
+ }
+
+ final lines = const LineSplitter().convert(utf8.decode(pageBytes));
+ final entries = <List<String>>[];
+ for (final line in lines) {
+ if (entries.isEmpty || _logRecordHeader.hasMatch(line)) {
+ entries.add([line]);
+ } else {
+ entries.last.add(line);
+ }
+ }
+ return (
+ start: position,
+ entries: [for (final entry in entries) entry.join('\n')],
+ firstEntryContinuesPrevious:
+ lines.isNotEmpty && !_logRecordHeader.hasMatch(lines.first),
+ );
+ } finally {
+ await handle.close();
+ }
+ }
+}
diff --git a/mobile/packages/logging/lib/logging.dart b/mobile/packages/logging/lib/logging.dart
index c3d827a240..6f014689d3 100644
--- a/mobile/packages/logging/lib/logging.dart
+++ b/mobile/packages/logging/lib/logging.dart
@@ -1,4 +1,5 @@
export 'package:logging/logging.dart';
+export 'log_file_reader.dart';
export 'super_logging.dart';
export 'tunneled_transport.dart';
diff --git a/mobile/packages/logging/test/log_file_reader_test.dart b/mobile/packages/logging/test/log_file_reader_test.dart
new file mode 100644
index 0000000000..463bda355d
--- /dev/null
+++ b/mobile/packages/logging/test/log_file_reader_test.dart
@@ -0,0 +1,33 @@
+import 'dart:io';
+
+import 'package:ente_logging/logging.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ test('reads every multiline entry across backward pages', () async {
+ final directory = await Directory.systemTemp.createTemp('log-reader-');
+ addTearDown(() => directory.delete(recursive: true));
+
+ const first =
+ '[main][INFO] [2026-08-08 09:12:00.000000] Starting app in foreground';
+ const latest =
+ '[bg] [sync] [SEVERE] [2026-08-08 22:23:00.000000] Latest record';
+ final padding = List.filled(40, 'x').join();
+ final continuation = List.generate(5000, (index) => '#$index $padding');
+ final firstEntry = [first, ...continuation].join('\n');
+ final file = File('${directory.path}/today.txt');
+ await file.writeAsString('$firstEntry\n$latest\n');
+
+ final reader = LogFileReader(file);
+ await reader.reset();
+ final entries = <LogFileEntry>[];
+ while (reader.hasMore) {
+ entries.addAll(await reader.readPreviousPage());
+ }
+
+ expect(entries.map((entry) => entry.text), [latest, firstEntry]);
+ expect(entries.first.loggerName, 'sync');
+ expect(entries.last.loggerName, 'main');
+ expect(entries.last.message, 'Starting app in foreground');
+ });
+}
diff --git a/mobile/packages/ui/lib/pages/log_file_viewer.dart b/mobile/packages/ui/lib/pages/log_file_viewer.dart
index 3a40664efa..e7b306a21f 100644
--- a/mobile/packages/ui/lib/pages/log_file_viewer.dart
+++ b/mobile/packages/ui/lib/pages/log_file_viewer.dart
@@ -1,65 +1,554 @@
import 'dart:io';
+import 'dart:math';
+import 'package:ente_components/components/popup_menu_component.dart';
+import 'package:ente_logging/logging.dart';
+import 'package:ente_strings/ente_strings.dart';
import 'package:ente_ui/components/loading_widget.dart';
-import 'package:flutter/cupertino.dart';
+import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
+import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
+
+const _foregroundSessionMessage = 'Starting app in foreground';
class LogFileViewer extends StatefulWidget {
- final File file;
const LogFileViewer(this.file, {super.key});
+ final File file;
+
@override
State<LogFileViewer> createState() => _LogFileViewerState();
}
class _LogFileViewerState extends State<LogFileViewer> {
- String? _logs;
+ final _itemPositionsListener = ItemPositionsListener.create();
+ final _itemScrollController = ItemScrollController();
+ final _scrollMetrics = ValueNotifier((extent: 1.0, position: 1.0));
+ final _entries = <LogFileEntry>[];
+ Future<void>? _activeLoad;
+ late final LogFileReader _reader;
+ int _generation = 0;
+ bool _loadFailed = false;
+ bool _isLoading = false;
+ bool _isRefreshing = false;
+ bool _isSearching = false;
+ bool _needsMatchJump = false;
+ int _matchIndex = 0;
+ String _query = '';
+
@override
void initState() {
- widget.file.readAsString().then((logs) {
+ super.initState();
+ _reader = LogFileReader(widget.file);
+ _itemPositionsListener.itemPositions.addListener(_handleItemPositions);
+ _refresh();
+ }
+
+ @override
+ void dispose() {
+ _generation++;
+ _itemPositionsListener.itemPositions.removeListener(_handleItemPositions);
+ _scrollMetrics.dispose();
+ super.dispose();
+ }
+
+ Future<void> _refresh() async {
+ if (_isRefreshing) return;
+ final generation = ++_generation;
+ setState(() {
+ _loadFailed = false;
+ _isLoading = true;
+ _isRefreshing = true;
+ });
+ final activeLoad = _activeLoad;
+ if (activeLoad != null) await activeLoad;
+ if (!mounted || generation != _generation) return;
+
+ try {
+ await _reader.reset();
+ if (!mounted || generation != _generation) return;
setState(() {
- _logs = logs;
+ _entries.clear();
+ _matchIndex = 0;
+ _needsMatchJump = _query.isNotEmpty;
+ _isLoading = _reader.hasMore;
+ _isRefreshing = false;
});
+ await _loadOlder();
+ if (_query.isNotEmpty) await _loadAllEntries();
+ } catch (_) {
+ if (mounted && generation == _generation) {
+ setState(() {
+ _loadFailed = true;
+ _isLoading = false;
+ _isRefreshing = false;
+ });
+ }
+ }
+ }
+
+ Future<void> _loadOlder() {
+ if (_isRefreshing || _loadFailed || !_reader.hasMore) {
+ return Future.value();
+ }
+ final activeLoad = _activeLoad;
+ if (activeLoad != null) return activeLoad;
+
+ final generation = _generation;
+ late final Future<void> load;
+ load = _performLoad(generation).whenComplete(() {
+ if (identical(_activeLoad, load)) _activeLoad = null;
});
- super.initState();
+ _activeLoad = load;
+ return load;
+ }
+
+ Future<void> _performLoad(int generation) async {
+ setState(() => _isLoading = true);
+ try {
+ final entries = await _reader.readPreviousPage();
+ if (!mounted || generation != _generation) return;
+ setState(() => _entries.addAll(entries));
+ _jumpToFirstMatchIfNeeded();
+ } catch (_) {
+ if (mounted && generation == _generation) {
+ setState(() => _loadFailed = true);
+ }
+ } finally {
+ if (mounted && generation == _generation) {
+ setState(() => _isLoading = false);
+ }
+ }
+ }
+
+ Future<void> _loadAllEntries() async {
+ final generation = _generation;
+ while (mounted &&
+ generation == _generation &&
+ _isSearching &&
+ _query.isNotEmpty &&
+ !_isRefreshing &&
+ !_loadFailed &&
+ _reader.hasMore) {
+ await _loadOlder();
+ }
+ }
+
+ void _handleItemPositions() {
+ final positions = _itemPositionsListener.itemPositions.value;
+ if (positions.isEmpty) return;
+ final oldestVisible = positions
+ .map((position) => position.index)
+ .reduce(max);
+ if (_entries.length - oldestVisible < 5) _loadOlder();
+
+ final logPositions = positions.where(
+ (position) => position.index < _entries.length,
+ );
+ if (logPositions.isEmpty) return;
+ final newestVisible = logPositions
+ .map((position) => position.index)
+ .reduce(min);
+ final oldestLogVisible = logPositions
+ .map((position) => position.index)
+ .reduce(max);
+ final denominator = max(_entries.length - 1, 1);
+ _scrollMetrics.value = (
+ extent: ((oldestLogVisible - newestVisible + 1) / _entries.length).clamp(
+ 0.04,
+ 1.0,
+ ),
+ position:
+ 1 -
+ ((newestVisible + oldestLogVisible) / 2 / denominator).clamp(0, 1),
+ );
+ }
+
+ void _toggleSearch() {
+ setState(() {
+ _isSearching = !_isSearching;
+ if (!_isSearching) {
+ _needsMatchJump = false;
+ _matchIndex = 0;
+ _query = '';
+ }
+ });
+ }
+
+ void _moveToMatch(int offset, List<int> matches) {
+ setState(() => _matchIndex = (_matchIndex + offset) % matches.length);
+ _scrollToEntry(matches[_matchIndex]);
+ }
+
+ void _jumpToFirstMatchIfNeeded() {
+ if (!_needsMatchJump || _query.isEmpty) return;
+ final matches = _matchingEntryIndices(
+ RegExp(RegExp.escape(_query), caseSensitive: false),
+ );
+ if (matches.isEmpty) return;
+ _needsMatchJump = false;
+ _scrollToEntry(matches.first);
+ }
+
+ List<int> _matchingEntryIndices(RegExp searchPattern) {
+ return [
+ for (var index = 0; index < _entries.length; index++)
+ if (searchPattern.hasMatch(_entries[index].text)) index,
+ ];
+ }
+
+ List<int> _sessionEntryIndices() {
+ return [
+ for (var index = 0; index < _entries.length; index++)
+ if (_entries[index].isForegroundSession) index,
+ ];
+ }
+
+ void _scrollToEntry(int index) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || !_itemScrollController.isAttached) return;
+ _itemScrollController.jumpTo(index: index, alignment: 0.5);
+ });
+ }
+
+ String _formatSessionTime(BuildContext context, LogFileEntry entry) {
+ final date = entry.timestamp?.toLocal();
+ if (date == null) return _foregroundSessionMessage;
+ final localizations = MaterialLocalizations.of(context);
+ return '${localizations.formatCompactDate(date)} Β· '
+ '${localizations.formatTimeOfDay(TimeOfDay.fromDateTime(date))}';
+ }
+
+ Future<List<EntePopupMenuOption<int>>> _sessionOptions() async {
+ final generation = _generation;
+ while (mounted &&
+ generation == _generation &&
+ !_isRefreshing &&
+ !_loadFailed &&
+ _reader.hasMore) {
+ await _loadOlder();
+ }
+ if (!mounted || generation != _generation) return [];
+ return [
+ for (final index in _sessionEntryIndices())
+ EntePopupMenuOption(
+ value: index,
+ label: _formatSessionTime(context, _entries[index]),
+ leadingWidget: const Icon(Icons.play_circle_outline, size: 18),
+ ),
+ ];
}
@override
Widget build(BuildContext context) {
+ final searchPattern = _query.isEmpty
+ ? null
+ : RegExp(RegExp.escape(_query), caseSensitive: false);
+ final matches = searchPattern == null
+ ? const <int>[]
+ : _matchingEntryIndices(searchPattern);
+ final sessions = _sessionEntryIndices();
return Scaffold(
appBar: AppBar(
elevation: 0,
scrolledUnderElevation: 0,
surfaceTintColor: Colors.transparent,
- title: const Text("Today's logs"),
+ title: _isSearching
+ ? TextField(
+ autofocus: true,
+ decoration: InputDecoration(
+ border: InputBorder.none,
+ hintText: context.strings.search,
+ suffixText: _query.isEmpty
+ ? null
+ : matches.isEmpty
+ ? '0'
+ : '${_matchIndex + 1}/${matches.length}',
+ ),
+ onChanged: (query) {
+ setState(() {
+ _matchIndex = 0;
+ _needsMatchJump = query.isNotEmpty;
+ _query = query;
+ });
+ if (query.isNotEmpty) _loadAllEntries();
+ _jumpToFirstMatchIfNeeded();
+ },
+ )
+ : Text(context.strings.todaysLogs),
+ actions: [
+ if (_isSearching) ...[
+ IconButton(
+ icon: const Icon(Icons.keyboard_arrow_up),
+ tooltip: context.strings.previous,
+ onPressed: matches.length > 1
+ ? () => _moveToMatch(1, matches)
+ : null,
+ ),
+ IconButton(
+ icon: const Icon(Icons.keyboard_arrow_down),
+ tooltip: context.strings.next,
+ onPressed: matches.length > 1
+ ? () => _moveToMatch(-1, matches)
+ : null,
+ ),
+ IconButton(
+ icon: const Icon(Icons.close),
+ tooltip: MaterialLocalizations.of(context).closeButtonTooltip,
+ onPressed: _toggleSearch,
+ ),
+ ] else ...[
+ if (sessions.length > 1 || (!_loadFailed && _reader.hasMore))
+ EntePopupMenuButton<int>(
+ optionsBuilder: _sessionOptions,
+ onSelected: _scrollToEntry,
+ child: Tooltip(
+ message: context.strings.logs,
+ child: const SizedBox.square(
+ dimension: kMinInteractiveDimension,
+ child: Icon(Icons.history),
+ ),
+ ),
+ ),
+ IconButton(
+ icon: const Icon(Icons.search),
+ tooltip: context.strings.search,
+ onPressed: _toggleSearch,
+ ),
+ IconButton(
+ icon: const Icon(Icons.refresh),
+ tooltip: MaterialLocalizations.of(
+ context,
+ ).refreshIndicatorSemanticLabel,
+ onPressed: _refresh,
+ ),
+ ],
+ ],
),
- body: _getBody(),
+ body: _buildLogList(context, searchPattern, sessions),
);
}
- Widget _getBody() {
- if (_logs == null) {
- return const EnteLoadingWidget();
+ Widget _buildLogList(
+ BuildContext context,
+ RegExp? searchPattern,
+ List<int> sessions,
+ ) {
+ if (_loadFailed && _entries.isEmpty) {
+ return Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(context.strings.somethingWentWrong),
+ TextButton(onPressed: _refresh, child: Text(context.strings.retry)),
+ ],
+ ),
+ );
+ }
+
+ if (_entries.isEmpty) {
+ if (_isLoading) return const EnteLoadingWidget();
+ return Center(child: Text(context.strings.noResultsFound));
}
- return Container(
- padding: const EdgeInsets.only(left: 12, top: 8, right: 12),
- child: SingleChildScrollView(
- child: SelectableRegion(
- focusNode: FocusNode(),
- selectionControls: Platform.isAndroid
- ? materialTextSelectionControls
- : Platform.isIOS
- ? cupertinoTextSelectionControls
- : desktopTextSelectionControls,
- child: Text(
- _logs!,
- style: const TextStyle(
- fontFeatures: [FontFeature.tabularFigures()],
- height: 1.2,
+
+ final style = Theme.of(context).textTheme.bodyMedium?.copyWith(
+ fontFamily: 'monospace',
+ fontSize: 11,
+ fontWeight: FontWeight.w400,
+ height: 1.35,
+ );
+ return SafeArea(
+ top: false,
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ SelectionArea(
+ child: ScrollablePositionedList.builder(
+ itemScrollController: _itemScrollController,
+ itemPositionsListener: _itemPositionsListener,
+ reverse: true,
+ padding: const EdgeInsets.fromLTRB(12, 8, 18, 16),
+ itemCount: _entries.length + (_isLoading ? 1 : 0),
+ itemBuilder: (context, index) {
+ if (index == _entries.length) {
+ return const Padding(
+ padding: EdgeInsets.all(16),
+ child: Center(child: EnteLoadingWidget()),
+ );
+ }
+ return _buildLogEntry(
+ context,
+ _entries[index],
+ searchPattern,
+ style,
+ );
+ },
),
),
- ),
+ Positioned(
+ top: 4,
+ right: 0,
+ bottom: 4,
+ width: 14,
+ child: _LogScrollbar(
+ itemCount: _entries.length,
+ metrics: _scrollMetrics,
+ sessionIndices: sessions,
+ onJump: _scrollToEntry,
+ ),
+ ),
+ ],
),
);
}
+
+ Widget _buildLogEntry(
+ BuildContext context,
+ LogFileEntry entry,
+ RegExp? searchPattern,
+ TextStyle? style,
+ ) {
+ if (entry.isForegroundSession) {
+ final colors = Theme.of(context).colorScheme;
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Row(
+ children: [
+ Expanded(child: Divider(color: colors.outlineVariant)),
+ const SizedBox(width: 8),
+ Icon(Icons.play_circle_outline, size: 16, color: colors.primary),
+ const SizedBox(width: 4),
+ Text(
+ _formatSessionTime(context, entry),
+ style: Theme.of(context).textTheme.labelSmall,
+ ),
+ const SizedBox(width: 8),
+ Expanded(child: Divider(color: colors.outlineVariant)),
+ ],
+ ),
+ );
+ }
+
+ return searchPattern == null
+ ? Text(entry.text, style: style)
+ : Text.rich(
+ _highlightMatches(context, entry.text, searchPattern, style),
+ );
+ }
+
+ TextSpan _highlightMatches(
+ BuildContext context,
+ String text,
+ RegExp searchPattern,
+ TextStyle? style,
+ ) {
+ final spans = <TextSpan>[];
+ final colors = Theme.of(context).colorScheme;
+ final highlightStyle = TextStyle(
+ backgroundColor: colors.primaryContainer,
+ color: colors.onPrimaryContainer,
+ );
+ var start = 0;
+ for (final match in searchPattern.allMatches(text)) {
+ if (match.start > start) {
+ spans.add(TextSpan(text: text.substring(start, match.start)));
+ }
+ spans.add(
+ TextSpan(
+ text: text.substring(match.start, match.end),
+ style: highlightStyle,
+ ),
+ );
+ start = match.end;
+ }
+ if (start < text.length) {
+ spans.add(TextSpan(text: text.substring(start)));
+ }
+ return TextSpan(style: style, children: spans);
+ }
+}
+
+extension on LogFileEntry {
+ bool get isForegroundSession =>
+ loggerName == 'main' && message == _foregroundSessionMessage;
+}
+
+class _LogScrollbar extends StatelessWidget {
+ const _LogScrollbar({
+ required this.itemCount,
+ required this.metrics,
+ required this.sessionIndices,
+ required this.onJump,
+ });
+
+ final int itemCount;
+ final ValueListenable<({double extent, double position})> metrics;
+ final List<int> sessionIndices;
+ final ValueChanged<int> onJump;
+
+ @override
+ Widget build(BuildContext context) {
+ return ValueListenableBuilder(
+ valueListenable: metrics,
+ builder: (context, value, _) {
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final height = constraints.maxHeight;
+ final thumbHeight = min(height, max(32.0, height * value.extent));
+ final thumbTop = (height - thumbHeight) * value.position;
+ final colors = Theme.of(context).colorScheme;
+
+ void jumpTo(Offset position) {
+ final fraction = (position.dy / height).clamp(0.0, 1.0);
+ onJump(((1 - fraction) * (itemCount - 1)).round());
+ }
+
+ return MouseRegion(
+ cursor: SystemMouseCursors.resizeUpDown,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTapDown: (details) => jumpTo(details.localPosition),
+ onVerticalDragStart: (details) => jumpTo(details.localPosition),
+ onVerticalDragUpdate: (details) =>
+ jumpTo(details.localPosition),
+ child: Stack(
+ children: [
+ Align(
+ alignment: Alignment.centerRight,
+ child: Container(
+ width: 2,
+ color: colors.outlineVariant.withValues(alpha: 0.6),
+ ),
+ ),
+ for (final index in sessionIndices)
+ Positioned(
+ top: (height - 2) * (1 - index / max(itemCount - 1, 1)),
+ right: 1,
+ child: Container(
+ width: 5,
+ height: 1,
+ color: colors.primary.withValues(alpha: 0.8),
+ ),
+ ),
+ Positioned(
+ top: thumbTop,
+ right: 0,
+ child: Container(
+ width: 5,
+ height: thumbHeight,
+ decoration: BoxDecoration(
+ color: colors.onSurfaceVariant.withValues(alpha: 0.7),
+ borderRadius: BorderRadius.circular(3),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ },
+ );
+ }
}
diff --git a/mobile/packages/ui/pubspec.yaml b/mobile/packages/ui/pubspec.yaml
index 9010d2c9cf..375465c3a1 100644
--- a/mobile/packages/ui/pubspec.yaml
+++ b/mobile/packages/ui/pubspec.yaml
@@ -27,6 +27,7 @@ dependencies:
hugeicons: 1.1.7
modal_bottom_sheet: 3.0.0
package_info_plus: 8.3.1
+ scrollable_positioned_list: 0.3.8
url_launcher: 6.3.2
dev_dependencies:
diff --git a/mobile/packages/utils/lib/email_util.dart b/mobile/packages/utils/lib/email_util.dart
index b8a39910b4..ae5a43e9ee 100644
--- a/mobile/packages/utils/lib/email_util.dart
+++ b/mobile/packages/utils/lib/email_util.dart
@@ -62,22 +62,15 @@ Future<void> sendLogs(
}
},
),
- //isInAlert is false here as we don't want to the dialog to dismiss
- //on pressing this button
ButtonWidget(
buttonType: ButtonType.secondary,
labelText: context.strings.viewLogs,
buttonAction: ButtonAction.second,
onTap: () async {
- // ignore: unawaited_futures
- showDialog(
- useRootNavigator: false,
- context: context,
- builder: (BuildContext context) {
- return LogFileViewer(SuperLogging.logFile!);
- },
- barrierColor: Colors.black87,
- barrierDismissible: false,
+ await Navigator.of(context).push(
+ MaterialPageRoute(
+ builder: (_) => LogFileViewer(SuperLogging.logFile!),
+ ),
);
},
),