diff --git a/PLAN.md b/PLAN.md index 7db00fa..3dc9a75 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,18 @@ --- +## 0.6.7 右侧栏浏览器与图标标签(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 浏览器 | 右侧栏新增【浏览器】页:地址栏(后退 / 前进 / 输入网址 / 前进按钮 / 停止或刷新)、历史记录、在系统浏览器中打开;空状态提供 `localhost:3000`、`5173`、`8080` 快捷入口;页面用嵌入式 WebView 打开(Android/iOS),桌面显示仅移动端可用的提示 | +| 地址栏 | 自动补 `http://`(localhost/回环地址)或 `https://`,加载错误时显示错误条和重试;地址字段把光标放在末尾,窄栏也能看到刚访问的部分 | +| 标签 | 右侧栏顶部由文字标签改为**图标 + tooltip**(文件、项目知识、终端、浏览器),项目多/栏窄时不再截断文字;四个页签用懒加载的 Offstage 栈保持各自状态(浏览器页面切走再切回不会重新加载) | +| 明文 | Android 允许 WebView 加载 HTTP(`usesCleartextTraffic`),本地开发服务器可直接预览 | +| 版本 | **0.6.7(code 607)** | + +--- + ## 0.6.6 图片查看器:保存/分享与隐藏顶栏(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index aa04caa..d8f27a8 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in Flutter to compare mobile UI maturity. -Status: 0.6.6 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.6.7 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link over the OpenChamber private relay with end-to-end encryption; the pairing link is pasted or scanned with the camera), session list with search and live diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index fe9eab4..e1bfc2a 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -14,7 +14,8 @@ + android:icon="@mipmap/ic_launcher" + android:usesCleartextTraffic="true"> result.notImplemented() } } + // The right sidebar's browser hands a page to the system browser. + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "openchamber/browser") + .setMethodCallHandler { call, result -> + when (call.method) { + "openUrl" -> { + val url = call.argument("url") + if (url.isNullOrBlank()) { + result.error("bad_args", "Missing URL", null) + return@setMethodCallHandler + } + try { + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) + result.success(true) + } catch (e: Exception) { + result.error("open_failed", e.message ?: "Could not open the URL", null) + } + } + else -> result.notImplemented() + } + } // Saving a conversation picture to the gallery and sharing it: both // need Android APIs (MediaStore, FileProvider) that a Dart package // would pull in another native dependency for. diff --git a/lib/l10n/zh.dart b/lib/l10n/zh.dart index a8c3422..d91f6bb 100644 --- a/lib/l10n/zh.dart +++ b/lib/l10n/zh.dart @@ -631,4 +631,17 @@ const Map chineseStrings = { 'Saved to Photos': '已保存到相册', "Couldn't save the picture": '无法保存图片', 'Storage permission is required to save the picture': '保存图片需要存储权限', + + // browser + 'Browser': '浏览器', + 'Enter a URL': '输入网址', + 'Web browser': '网页浏览器', + 'Enter a URL above to start browsing': '在上方输入网址开始浏览', + 'Browser is only available on Android and iOS': '浏览器面板仅支持 Android 和 iOS', + 'Open in system browser': '在系统浏览器中打开', + 'Forward': '前进', + 'Reload': '重新加载', + 'History': '历史记录', + 'Invalid URL': '无效的网址', + 'Could not open the browser: {0}': '无法打开浏览器:{0}', }; diff --git a/lib/screens/browser_panel.dart b/lib/screens/browser_panel.dart new file mode 100644 index 0000000..e4dd759 --- /dev/null +++ b/lib/screens/browser_panel.dart @@ -0,0 +1,343 @@ +// The right sidebar's web browser: an address bar over an embedded WebView, +// with history navigation, reload/stop and opening the page in the system +// browser. The panel keeps its page while another tab is shown (the tab stack +// keeps it alive). +import 'dart:io' show Platform; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:webview_flutter/webview_flutter.dart'; + +import '../l10n.dart'; + +class BrowserPanel extends StatefulWidget { + const BrowserPanel({super.key}); + + @override + State createState() => _BrowserPanelState(); +} + +class _BrowserPanelState extends State { + static const MethodChannel _channel = MethodChannel('openchamber/browser'); + static const _quickLinks = [ + 'http://localhost:3000', + 'http://localhost:5173', + 'http://localhost:8080', + ]; + + final TextEditingController _url = TextEditingController(); + final List _history = []; + WebViewController? _web; + bool _loading = false; + bool _hasPage = false; + bool _canBack = false; + bool _canForward = false; + int _progress = 0; + String? _error; + + bool get _supported => Platform.isAndroid || Platform.isIOS; + + @override + void initState() { + super.initState(); + if (!_supported) return; + _web = WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setBackgroundColor(Colors.transparent) + ..setNavigationDelegate(NavigationDelegate( + onPageStarted: (url) { + if (!mounted) return; + setState(() { + _loading = true; + _hasPage = true; + _progress = 0; + _error = null; + _setUrl(url); + }); + _syncNavigation(); + }, + onPageFinished: (url) { + if (!mounted) return; + setState(() { + _loading = false; + _progress = 100; + _setUrl(url); + }); + _remember(url); + _syncNavigation(); + }, + onProgress: (value) { + if (mounted) setState(() => _progress = value); + }, + onUrlChange: (change) { + final url = change.url; + if (url != null && mounted) setState(() => _setUrl(url)); + }, + onWebResourceError: (error) { + if ((error.isForMainFrame ?? true) && mounted) { + setState(() => _error = error.description); + } + }, + )); + } + + @override + void dispose() { + _url.dispose(); + super.dispose(); + } + + Future _syncNavigation() async { + final web = _web; + if (web == null) return; + final back = await web.canGoBack(); + final forward = await web.canGoForward(); + if (!mounted) return; + setState(() { + _canBack = back; + _canForward = forward; + }); + } + + /// Puts [url] in the address field with the caret at its end, so the part + /// that was just visited stays visible in the narrow bar. + void _setUrl(String url) { + _url.value = TextEditingValue( + text: url, + selection: TextSelection.collapsed(offset: url.length), + ); + } + + void _remember(String url) { + if (url.isEmpty) return; + _history.remove(url); + _history.insert(0, url); + if (_history.length > 20) _history.removeLast(); + } + + void _navigate(String raw) { + var text = raw.trim(); + if (text.isEmpty) return; + if (!text.contains('://')) { + final host = text.split('/').first.split(':').first; + final local = host == 'localhost' || + host == '127.0.0.1' || + host == '[::1]' || + host == '0.0.0.0'; + text = '${local ? 'http' : 'https'}://$text'; + } + final uri = Uri.tryParse(text); + if (uri == null || !uri.hasAuthority) { + _snack(tr('Invalid URL')); + return; + } + FocusScope.of(context).unfocus(); + _setUrl(text); + _web?.loadRequest(uri); + } + + Future _openExternal() async { + if (!Platform.isAndroid) return; + final url = _url.text.trim(); + if (url.isEmpty) return; + try { + await _channel.invokeMethod('openUrl', {'url': url}); + } catch (e) { + if (mounted) _snack(trArgs('Could not open the browser: {0}', [e])); + } + } + + void _snack(String text) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: AppText(text))); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + if (!_supported) { + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.public_off, size: 40, color: theme.hintColor), + const SizedBox(height: 12), + const AppText( + 'Browser is only available on Android and iOS', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 13), + ), + ], + ), + ), + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _addressBar(theme), + if (_loading) + LinearProgressIndicator( + value: _progress > 0 && _progress < 100 ? _progress / 100 : null, + minHeight: 2, + ), + if (_error != null) _errorBar(theme), + Expanded( + // Keep the WebView attached even before the first address: a + // loadRequest on a controller with no platform view is lost. The + // empty state is an overlay until a page starts. + child: Stack( + children: [ + Positioned.fill(child: WebViewWidget(controller: _web!)), + if (!_hasPage) + Positioned.fill( + child: ColoredBox( + color: theme.colorScheme.surface, + child: _empty(theme), + ), + ), + ], + ), + ), + ], + ); + } + + Widget _addressBar(ThemeData theme) { + final web = _web; + return Padding( + padding: const EdgeInsets.fromLTRB(4, 6, 4, 6), + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back, size: 20), + tooltip: tr('Back'), + onPressed: _canBack ? () => web?.goBack() : null, + ), + IconButton( + icon: const Icon(Icons.arrow_forward, size: 20), + tooltip: tr('Forward'), + onPressed: _canForward ? () => web?.goForward() : null, + ), + Expanded( + child: TextField( + controller: _url, + keyboardType: TextInputType.url, + textInputAction: TextInputAction.go, + onSubmitted: _navigate, + decoration: InputDecoration( + isDense: true, + hintText: tr('Enter a URL'), + prefixIcon: const Icon(Icons.public, size: 18), + suffixIcon: IconButton( + icon: const Icon(Icons.arrow_forward, size: 18), + tooltip: tr('Go'), + onPressed: () => _navigate(_url.text), + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + ), + IconButton( + icon: Icon(_loading ? Icons.stop : Icons.refresh, size: 20), + tooltip: _loading ? tr('Stop') : tr('Reload'), + onPressed: _loading + ? () => web?.runJavaScript('window.stop()') + : web?.reload, + ), + if (Platform.isAndroid) + IconButton( + icon: const Icon(Icons.open_in_browser, size: 20), + tooltip: tr('Open in system browser'), + onPressed: _openExternal, + ), + if (_history.isNotEmpty) + PopupMenuButton( + icon: const Icon(Icons.history, size: 20), + tooltip: tr('History'), + onSelected: (url) { + _setUrl(url); + _navigate(url); + }, + itemBuilder: (_) => [ + for (final url in _history) + PopupMenuItem( + value: url, + child: Text(url, + maxLines: 1, overflow: TextOverflow.ellipsis), + ), + ], + ), + ], + ), + ); + } + + Widget _errorBar(ThemeData theme) { + return Container( + color: theme.colorScheme.errorContainer.withValues(alpha: 0.4), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Row( + children: [ + Icon(Icons.error_outline, + size: 16, color: theme.colorScheme.error), + const SizedBox(width: 8), + Expanded( + child: Text( + _error!, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: theme.colorScheme.error), + ), + ), + TextButton( + onPressed: () => _web?.reload(), + child: const AppText('Retry'), + ), + ], + ), + ); + } + + Widget _empty(ThemeData theme) { + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.public, size: 48, color: theme.hintColor), + const SizedBox(height: 12), + const AppText( + 'Web browser', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 4), + const AppText( + 'Enter a URL above to start browsing', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12.5), + ), + const SizedBox(height: 16), + Wrap( + spacing: 8, + runSpacing: 8, + alignment: WrapAlignment.center, + children: [ + for (final url in _quickLinks) + ActionChip( + label: Text(url), + onPressed: () => _navigate(url), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/files_panel.dart b/lib/screens/files_panel.dart index f66b023..8098a2b 100644 --- a/lib/screens/files_panel.dart +++ b/lib/screens/files_panel.dart @@ -12,6 +12,7 @@ import '../api/models.dart'; import '../api/transport.dart'; import '../state.dart'; import '../widgets/markdown_view.dart'; +import 'browser_panel.dart'; import 'knowledge_panel.dart'; import 'terminal_panel.dart'; import '../l10n.dart'; @@ -110,6 +111,10 @@ class _FilesPanelState extends State { int _tab = 0; + /// Tabs built at least once. Kept alive (offstage) so the browser, terminal + /// and knowledge pages keep their state when another tab is shown. + final Set _built = {0}; + @override void initState() { super.initState(); @@ -426,7 +431,20 @@ class _FilesPanelState extends State { children: [ _tabs(theme), const Divider(height: 1), - Expanded(child: _body(theme)), + Expanded( + child: Stack( + children: [ + for (var i = 0; i < 4; i++) + if (_built.contains(i)) + Positioned.fill( + child: Offstage( + offstage: _tab != i, + child: _tabBody(i, theme), + ), + ), + ], + ), + ), ], ), ), @@ -436,7 +454,14 @@ class _FilesPanelState extends State { /// The tab row is the panel's title now; the only global action left is /// closing the panel. Everything else belongs to the tab's own header. Widget _tabs(ThemeData theme) { - const labels = ['Files', 'Project knowledge', 'Terminal']; + // Icons only: four labels no longer fit a phone's panel width. The + // tooltips keep them identifiable. + const tabs = [ + (Icons.folder_outlined, 'Files'), + (Icons.menu_book_outlined, 'Project knowledge'), + (Icons.terminal, 'Terminal'), + (Icons.public, 'Browser'), + ]; return Padding( padding: const EdgeInsets.fromLTRB(12, 6, 2, 6), child: Row( @@ -449,11 +474,20 @@ class _FilesPanelState extends State { tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), segments: [ - for (var i = 0; i < labels.length; i++) - ButtonSegment(value: i, label: AppText(labels[i])), + for (var i = 0; i < tabs.length; i++) + ButtonSegment( + value: i, + icon: Tooltip( + message: tr(tabs[i].$2), + child: Icon(tabs[i].$1, size: 19), + ), + ), ], selected: {_tab}, - onSelectionChanged: (v) => setState(() => _tab = v.first), + onSelectionChanged: (v) => setState(() { + _tab = v.first; + _built.add(v.first); + }), ), ), IconButton( @@ -466,15 +500,17 @@ class _FilesPanelState extends State { ); } - Widget _body(ThemeData theme) { + Widget _tabBody(int index, ThemeData theme) { if (_root.isEmpty) { return const Center(child: AppText('This session has no directory')); } - switch (_tab) { + switch (index) { case 1: return KnowledgePanel(app: widget.app, directory: _root); case 2: return TerminalPanel(app: widget.app, directory: _root); + case 3: + return const BrowserPanel(); default: return Column( crossAxisAlignment: CrossAxisAlignment.stretch, diff --git a/pubspec.lock b/pubspec.lock index f20466d..8e05b96 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,10 +5,10 @@ packages: dependency: transitive description: name: android_file_picker - sha256: b8462091dcdd075511a842272374be2232e917ee2a51ecdba4aca02bff529482 + sha256: a4231d430c2d4f21a5024b69e7830309db79eac8ad20ddad03e7e721db42acb4 url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.2.2" archive: dependency: "direct main" description: @@ -53,10 +53,10 @@ packages: dependency: transitive description: name: camera_android_camerax - sha256: daefacb4c2c575426772a83ac312b93e2c49c003224962cddab904426dc04dbc + sha256: "5fc27a4825281bbd42120041900542bcb6c1c33a2668c22620c372c6a45713cb" url: "https://pub.dev" source: hosted - version: "0.7.6+2" + version: "0.7.6+4" camera_avfoundation: dependency: transitive description: @@ -101,10 +101,10 @@ packages: dependency: transitive description: name: cli_util - sha256: da2a2b22f919995eb427edab07725e2be0b1281ef26770f6ce3a213355565262 + sha256: d074d976edc0137e8730a064b22c8e5ea25c7ef7dde32bd94ab736934fb815f5 url: "https://pub.dev" source: hosted - version: "0.6.1" + version: "0.6.2" clock: dependency: transitive description: @@ -497,10 +497,10 @@ packages: dependency: transitive description: name: material_ui - sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab + sha256: "222670e8b0340f8dd873b21e7a5fcc7fd1872402faa3b21848cd6d96366a3c88" url: "https://pub.dev" source: hosted - version: "1.11.1" + version: "1.12.0" meta: dependency: transitive description: @@ -609,10 +609,10 @@ packages: dependency: transitive description: name: petitparser - sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790" + sha256: ce394bdb96208c2afb9b94b0987fccea1a0653fe43193cd70d15fc2f63b1f830 url: "https://pub.dev" source: hosted - version: "7.1.0" + version: "7.2.0" platform: dependency: transitive description: @@ -838,10 +838,10 @@ packages: dependency: transitive description: name: vector_graphics - sha256: "06081e4f2d8f17c306aa58989520694b463ad411bc7c7b93e76afa3e41ca17ac" + sha256: "51a00c9930636deb1c03e2ea7d47145fcc86e04a8824184f60596f4c94fd125a" url: "https://pub.dev" source: hosted - version: "1.3.1" + version: "1.3.2" vector_graphics_codec: dependency: transitive description: @@ -854,10 +854,10 @@ packages: dependency: transitive description: name: vector_graphics_compiler - sha256: "4a3f1ed88eb49c0ce9de15832256a3681eb4ce03350375ba588b5918ea3ed60a" + sha256: "921b9ed5fc647a7194dddf5451e97a551fd79077c78cc71577561009f620c061" url: "https://pub.dev" source: hosted - version: "1.3.7" + version: "1.3.8" vector_math: dependency: transitive description: @@ -882,6 +882,38 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.2" + webview_flutter: + dependency: "direct main" + description: + name: webview_flutter + sha256: d53e1ccf5516f25017e3c9d44c39034db352d20fa34fe200674270242c2c5111 + url: "https://pub.dev" + source: hosted + version: "4.14.1" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + sha256: "4de8b3d1ff4ebe1bdb42e68a5e4f809194a3cb0117a8f495f590004f00da3964" + url: "https://pub.dev" + source: hosted + version: "4.14.1" + webview_flutter_platform_interface: + dependency: transitive + description: + name: webview_flutter_platform_interface + sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04" + url: "https://pub.dev" + source: hosted + version: "2.15.1" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + sha256: acac45e0a8d7beb1d0805521f44842f406c46eb5a69410f53d935e3c62138afc + url: "https://pub.dev" + source: hosted + version: "3.27.2" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 472dbff..a6f6fad 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.6.6+606 +version: 0.6.7+607 environment: sdk: ^3.14.0 @@ -26,6 +26,7 @@ dependencies: package_info_plus: ^10.2.2 flutter_localizations: sdk: flutter + webview_flutter: ^4.14.1 dev_dependencies: flutter_test: sdk: flutter diff --git a/test/browser_panel_test.dart b/test/browser_panel_test.dart new file mode 100644 index 0000000..4a540fc --- /dev/null +++ b/test/browser_panel_test.dart @@ -0,0 +1,81 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/client.dart'; +import 'package:openchamber/api/transport.dart'; +import 'package:openchamber/l10n.dart'; +import 'package:openchamber/screens/browser_panel.dart'; +import 'package:openchamber/screens/files_panel.dart'; +import 'package:openchamber/state.dart'; + +class _FakeTransport implements Transport { + @override + Future send(TransportRequest r) async { + final body = switch (r.path) { + '/api/fs/list' => {'entries': []}, + _ => {}, + }; + return TransportResponse( + 200, + const {'content-type': 'application/json'}, + Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))), + ); + } + + @override + Future webSocket(String path, + {String? rawQuery, Map headers = const {}}) async => + throw UnimplementedError(); + + @override + void setBearerToken(String? token) {} + + @override + void close() {} +} + +void main() { + setUp(() => L10n.instance.apply(AppLanguage.en)); + tearDown(() => L10n.instance.apply(AppLanguage.zh)); + + testWidgets('the browser tab shows the mobile-only hint on desktop', + (tester) async { + await tester.pumpWidget(const MaterialApp( + home: Scaffold(body: BrowserPanel()), + )); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.public_off), findsOneWidget); + expect(find.text('Browser is only available on Android and iOS'), + findsOneWidget); + }); + + testWidgets('the panel tabs are icons with tooltips and open the browser', + (tester) async { + final app = AppState(); + addTearDown(app.dispose); + app.client = + Client(Uri.parse('http://test'), transport: _FakeTransport()); + + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: FilesPanel(app: app, directory: '/home/me')), + )); + await tester.pumpAndSettle(); + + for (final label in [ + 'Files', + 'Project knowledge', + 'Terminal', + 'Browser', + ]) { + expect(find.byTooltip(label), findsOneWidget, reason: label); + } + + await tester.tap(find.byTooltip('Browser')); + await tester.pumpAndSettle(); + expect(find.text('Browser is only available on Android and iOS'), + findsOneWidget); + }); +}