From e40383b290f0a7a0c14f848f597f11b84e060da1 Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Thu, 12 Nov 2026 00:57:40 +0800 Subject: [PATCH] feat: add Gitea Releases auto-update check (v1.0.3) --- .../com/lzxnone/code_editor/MainActivity.kt | 12 + lib/l10n/app_en.arb | 20 +- lib/l10n/app_localizations.dart | 66 +++++ lib/l10n/app_localizations_en.dart | 37 +++ lib/l10n/app_localizations_zh.dart | 35 +++ lib/l10n/app_zh.arb | 20 +- lib/providers/settings_provider.dart | 40 +++ lib/services/app_update_service.dart | 273 ++++++++++++++++++ lib/views/main_view.dart | 5 +- lib/views/settings_view.dart | 95 ++++++ pubspec.yaml | 2 +- test/app_update_service_test.dart | 75 +++++ 12 files changed, 676 insertions(+), 4 deletions(-) create mode 100644 lib/services/app_update_service.dart create mode 100644 test/app_update_service_test.dart diff --git a/android/app/src/main/kotlin/com/lzxnone/code_editor/MainActivity.kt b/android/app/src/main/kotlin/com/lzxnone/code_editor/MainActivity.kt index 4ac36a8..518b49a 100644 --- a/android/app/src/main/kotlin/com/lzxnone/code_editor/MainActivity.kt +++ b/android/app/src/main/kotlin/com/lzxnone/code_editor/MainActivity.kt @@ -1,5 +1,6 @@ package com.lzxnone.code_editor +import android.os.Build import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel @@ -14,6 +15,17 @@ class MainActivity : FlutterActivity() { "getNativeLibraryDir" -> { result.success(applicationInfo.nativeLibraryDir) } + "getAppVersion" -> { + try { + val info = packageManager.getPackageInfo(packageName, 0) + result.success(info.versionName ?: "") + } catch (e: Exception) { + result.success("") + } + } + "getSupportedAbis" -> { + result.success(Build.SUPPORTED_ABIS?.toList() ?: emptyList()) + } else -> result.notImplemented() } } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index a3b60c4..92f6b4c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1882,5 +1882,23 @@ "gitVerifyAndSave": "Verify & Save", "gitAuthTypeToken": "Personal Access Token", "gitAuthTypeSsh": "SSH Key Pair", - "gitPlatformGeneric": "Generic / Self-hosted Git" + "gitPlatformGeneric": "Generic / Self-hosted Git", + "aboutAndUpdatesSection": "About & Updates", + "appVersionLabel": "App Version", + "autoCheckUpdates": "Auto-check updates on launch", + "autoCheckUpdatesSubtitle": "Automatically check Gitea Releases when opening the app", + "checkForUpdates": "Check for Updates", + "checkingUpdates": "Checking for updates...", + "alreadyLatestVersion": "You are already on the latest version", + "updateCheckFailed": "Failed to check for updates, please check your network", + "newVersionAvailableTitle": "New Version {version}", + "@newVersionAvailableTitle": { + "placeholders": { + "version": { + "type": "String" + } + } + }, + "downloadUpdate": "Download Update", + "dontShowAgainForVersion": "Ignore This Version" } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 5f9f9c1..daa4c13 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -5733,6 +5733,72 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'通用 / 自建 Git'** String get gitPlatformGeneric; + + /// No description provided for @aboutAndUpdatesSection. + /// + /// In zh, this message translates to: + /// **'关于与更新'** + String get aboutAndUpdatesSection; + + /// No description provided for @appVersionLabel. + /// + /// In zh, this message translates to: + /// **'当前版本'** + String get appVersionLabel; + + /// No description provided for @autoCheckUpdates. + /// + /// In zh, this message translates to: + /// **'启动时自动检查更新'** + String get autoCheckUpdates; + + /// No description provided for @autoCheckUpdatesSubtitle. + /// + /// In zh, this message translates to: + /// **'每次打开应用时自动检查 Gitea 最新版本'** + String get autoCheckUpdatesSubtitle; + + /// No description provided for @checkForUpdates. + /// + /// In zh, this message translates to: + /// **'检查更新'** + String get checkForUpdates; + + /// No description provided for @checkingUpdates. + /// + /// In zh, this message translates to: + /// **'正在检查更新...'** + String get checkingUpdates; + + /// No description provided for @alreadyLatestVersion. + /// + /// In zh, this message translates to: + /// **'当前已是最新版本'** + String get alreadyLatestVersion; + + /// No description provided for @updateCheckFailed. + /// + /// In zh, this message translates to: + /// **'检查更新失败,请检查网络连接'** + String get updateCheckFailed; + + /// No description provided for @newVersionAvailableTitle. + /// + /// In zh, this message translates to: + /// **'发现新版本 {version}'** + String newVersionAvailableTitle(String version); + + /// No description provided for @downloadUpdate. + /// + /// In zh, this message translates to: + /// **'前往下载'** + String get downloadUpdate; + + /// No description provided for @dontShowAgainForVersion. + /// + /// In zh, this message translates to: + /// **'不再提示'** + String get dontShowAgainForVersion; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0e924e0..3d6d9ab 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -3389,4 +3389,41 @@ class AppLocalizationsEn extends AppLocalizations { @override String get gitPlatformGeneric => 'Generic / Self-hosted Git'; + + @override + String get aboutAndUpdatesSection => 'About & Updates'; + + @override + String get appVersionLabel => 'App Version'; + + @override + String get autoCheckUpdates => 'Auto-check updates on launch'; + + @override + String get autoCheckUpdatesSubtitle => + 'Automatically check Gitea Releases when opening the app'; + + @override + String get checkForUpdates => 'Check for Updates'; + + @override + String get checkingUpdates => 'Checking for updates...'; + + @override + String get alreadyLatestVersion => 'You are already on the latest version'; + + @override + String get updateCheckFailed => + 'Failed to check for updates, please check your network'; + + @override + String newVersionAvailableTitle(String version) { + return 'New Version $version'; + } + + @override + String get downloadUpdate => 'Download Update'; + + @override + String get dontShowAgainForVersion => 'Ignore This Version'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 717499a..22d9804 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -3260,4 +3260,39 @@ class AppLocalizationsZh extends AppLocalizations { @override String get gitPlatformGeneric => '通用 / 自建 Git'; + + @override + String get aboutAndUpdatesSection => '关于与更新'; + + @override + String get appVersionLabel => '当前版本'; + + @override + String get autoCheckUpdates => '启动时自动检查更新'; + + @override + String get autoCheckUpdatesSubtitle => '每次打开应用时自动检查 Gitea 最新版本'; + + @override + String get checkForUpdates => '检查更新'; + + @override + String get checkingUpdates => '正在检查更新...'; + + @override + String get alreadyLatestVersion => '当前已是最新版本'; + + @override + String get updateCheckFailed => '检查更新失败,请检查网络连接'; + + @override + String newVersionAvailableTitle(String version) { + return '发现新版本 $version'; + } + + @override + String get downloadUpdate => '前往下载'; + + @override + String get dontShowAgainForVersion => '不再提示'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 4e51d36..c661933 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1882,5 +1882,23 @@ "gitVerifyAndSave": "验证并保存", "gitAuthTypeToken": "个人访问令牌", "gitAuthTypeSsh": "SSH 密钥对", - "gitPlatformGeneric": "通用 / 自建 Git" + "gitPlatformGeneric": "通用 / 自建 Git", + "aboutAndUpdatesSection": "关于与更新", + "appVersionLabel": "当前版本", + "autoCheckUpdates": "启动时自动检查更新", + "autoCheckUpdatesSubtitle": "每次打开应用时自动检查 Gitea 最新版本", + "checkForUpdates": "检查更新", + "checkingUpdates": "正在检查更新...", + "alreadyLatestVersion": "当前已是最新版本", + "updateCheckFailed": "检查更新失败,请检查网络连接", + "newVersionAvailableTitle": "发现新版本 {version}", + "@newVersionAvailableTitle": { + "placeholders": { + "version": { + "type": "String" + } + } + }, + "downloadUpdate": "前往下载", + "dontShowAgainForVersion": "不再提示" } \ No newline at end of file diff --git a/lib/providers/settings_provider.dart b/lib/providers/settings_provider.dart index 5fea564..9cc60c2 100644 --- a/lib/providers/settings_provider.dart +++ b/lib/providers/settings_provider.dart @@ -57,6 +57,10 @@ class SettingsProvider extends ChangeNotifier { static const String _keyContainerRuntimeMode = 'container_runtime_mode'; static const String _keyHasPromptedRootRequest = 'has_prompted_root_request'; + //应用更新 + static const String _keyAutoCheckUpdate = 'auto_check_update'; + static const String _keySuppressedUpdateVersionCode = 'suppressed_update_version_code'; + /// 字号配置常量(编辑区与终端统一) static const double minFontSize = 8.0; static const double maxFontSize = 30.0; @@ -89,6 +93,8 @@ class SettingsProvider extends ChangeNotifier { bool _enableCodeDiagnostics = true; ContainerRuntimeMode _containerRuntimeMode = ContainerRuntimeMode.auto; bool _hasPromptedRootRequest = false; + bool _autoCheckUpdate = true; + int _suppressedUpdateVersionCode = 0; Locale? _locale; bool get showHiddenFiles => _showHiddenFiles; @@ -99,6 +105,8 @@ class SettingsProvider extends ChangeNotifier { bool get enableCodeDiagnostics => _enableCodeDiagnostics; ContainerRuntimeMode get containerRuntimeMode => _containerRuntimeMode; bool get hasPromptedRootRequest => _hasPromptedRootRequest; + bool get autoCheckUpdate => _autoCheckUpdate; + int get suppressedUpdateVersionCode => _suppressedUpdateVersionCode; ThemeMode get appThemeMode => _appThemeMode; Color get appThemeColor => _appThemeColor; @@ -360,6 +368,16 @@ class SettingsProvider extends ChangeNotifier { _hasPromptedRootRequest = savedPromptedRoot; } + //应用更新配置 + final savedAutoCheckUpdate = prefs.getBool(_keyAutoCheckUpdate); + if (savedAutoCheckUpdate != null) { + _autoCheckUpdate = savedAutoCheckUpdate; + } + final savedSuppressedUpdateVersion = prefs.getInt(_keySuppressedUpdateVersionCode); + if (savedSuppressedUpdateVersion != null) { + _suppressedUpdateVersionCode = savedSuppressedUpdateVersion; + } + notifyListeners(); }catch (_) {} } @@ -386,6 +404,28 @@ class SettingsProvider extends ChangeNotifier { } catch (_) {} } + /// 设置是否启动时自动检查应用更新 + Future setAutoCheckUpdate(bool enabled) async { + if (_autoCheckUpdate == enabled) return; + _autoCheckUpdate = enabled; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_keyAutoCheckUpdate, enabled); + } catch (_) {} + } + + /// 记录用户选择“不再提示”的版本号 + Future setSuppressedUpdateVersionCode(int versionCode) async { + if (_suppressedUpdateVersionCode == versionCode) return; + _suppressedUpdateVersionCode = versionCode; + notifyListeners(); + try { + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt(_keySuppressedUpdateVersionCode, versionCode); + } catch (_) {} + } + Future setAppThemeMode(ThemeMode mode) async { if(_appThemeMode == mode) return; _appThemeMode = mode; diff --git a/lib/services/app_update_service.dart b/lib/services/app_update_service.dart new file mode 100644 index 0000000..aa32f88 --- /dev/null +++ b/lib/services/app_update_service.dart @@ -0,0 +1,273 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/providers/settings_provider.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:url_launcher/url_launcher.dart'; + +/// 应用版本更新信息(Gitea Releases) +class AppUpdateInfo { + const AppUpdateInfo({ + required this.versionCode, + required this.versionName, + required this.changelog, + required this.downloadUrl, + required this.hasUpdate, + this.apkSize = '', + }); + + final int versionCode; + final String versionName; + final String changelog; + final String downloadUrl; + final bool hasUpdate; + final String apkSize; +} + +/// 基于自建 Gitea Releases 的版本更新检查服务 +class AppUpdateService { + AppUpdateService._(); + + static final AppUpdateService instance = AppUpdateService._(); + + static const String fallbackVersionName = '1.0.3'; + static const String updateUrl = + 'https://gitea.lzxnone.cloud/api/v1/repos/lzxnone/LN-Code-Editor/releases/latest'; + static const MethodChannel _nativeChannel = + MethodChannel('com.lzxnone.code_editor/native'); + + String? _cachedAppVersion; + + Future getCurrentAppVersion() async { + if (_cachedAppVersion != null && _cachedAppVersion!.isNotEmpty) { + return _cachedAppVersion!; + } + try { + final version = await _nativeChannel.invokeMethod('getAppVersion'); + if (version != null && version.trim().isNotEmpty) { + _cachedAppVersion = version.trim(); + return _cachedAppVersion!; + } + } catch (_) {} + return fallbackVersionName; + } + + Future> _getSupportedAbis() async { + try { + final abis = await _nativeChannel.invokeListMethod('getSupportedAbis'); + if (abis != null) return abis; + } catch (_) {} + return const []; + } + + /// 检查 Gitea 最新 Release 是否有新版本 + Future checkUpdate() async { + final currentVersion = await getCurrentAppVersion(); + final supportedAbis = await _getSupportedAbis(); + + final client = HttpClient()..connectionTimeout = const Duration(seconds: 8); + try { + final request = await client.getUrl(Uri.parse(updateUrl)); + request.headers.set(HttpHeaders.acceptHeader, 'application/json'); + request.headers.set(HttpHeaders.userAgentHeader, 'LN-Code-Editor-Android'); + + final response = await request.close().timeout(const Duration(seconds: 8)); + final body = await utf8.decodeStream(response); + if (response.statusCode != HttpStatus.ok) { + throw HttpException('HTTP ${response.statusCode}', uri: Uri.parse(updateUrl)); + } + return parseReleaseJson( + body, + currentVersion: currentVersion, + supportedAbis: supportedAbis, + ); + } finally { + client.close(force: true); + } + } + + /// 启动静默自动检查,发现新版且未被抑制时弹窗提醒 + Future checkAutoUpdate( + BuildContext context, + SettingsProvider settings, + ) async { + if (!settings.autoCheckUpdate) return; + try { + final info = await checkUpdate(); + if (!context.mounted) return; + if (info.hasUpdate && + info.versionCode > settings.suppressedUpdateVersionCode) { + await showUpdateDialog(context, info, settings: settings); + } + } catch (_) {} + } + + /// 展示更新弹窗 + Future showUpdateDialog( + BuildContext context, + AppUpdateInfo info, { + SettingsProvider? settings, + }) async { + if (!context.mounted) return; + final l10n = AppLocalizations.of(context)!; + final displayVersion = info.versionName.toLowerCase().startsWith('v') + ? 'V${info.versionName.substring(1)}' + : 'V${info.versionName}'; + + await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: Text(l10n.newVersionAvailableTitle(displayVersion)), + content: ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 280), + child: SingleChildScrollView( + child: Text(info.changelog), + ), + ), + actions: [ + if (settings != null) + TextButton( + onPressed: () { + settings.setSuppressedUpdateVersionCode(info.versionCode); + Navigator.of(dialogContext).pop(); + }, + child: Text(l10n.dontShowAgainForVersion), + ), + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: () async { + Navigator.of(dialogContext).pop(); + if (info.downloadUrl.isNotEmpty) { + await launchUrl( + Uri.parse(info.downloadUrl), + mode: LaunchMode.externalApplication, + ); + } + }, + child: Text(l10n.downloadUpdate), + ), + ], + ); + }, + ); + } + + @visibleForTesting + static AppUpdateInfo parseReleaseJson( + String rawJson, { + required String currentVersion, + List supportedAbis = const [], + }) { + final json = jsonDecode(rawJson) as Map; + final rawTag = (json['tag_name'] as String? ?? '').trim(); + final versionName = rawTag.replaceFirst(RegExp(r'^[vV]'), ''); + final versionCode = parseVersionCode(versionName); + final rawBody = (json['body'] as String? ?? '').trim(); + final releaseName = (json['name'] as String? ?? '').trim(); + final changelog = rawBody.isNotEmpty ? rawBody : releaseName; + final fallbackUrl = (json['html_url'] as String? ?? '').trim(); + + final (downloadUrl, apkSize) = _selectApkAsset( + json['assets'], + supportedAbis: supportedAbis, + fallbackUrl: fallbackUrl, + ); + + return AppUpdateInfo( + versionCode: versionCode, + versionName: versionName, + changelog: changelog, + downloadUrl: downloadUrl, + hasUpdate: isNewerVersion(versionName, currentVersion), + apkSize: apkSize, + ); + } + + static (String, String) _selectApkAsset( + dynamic assets, { + required List supportedAbis, + required String fallbackUrl, + }) { + if (assets is! List || assets.isEmpty) { + return (fallbackUrl, ''); + } + + final apkAssets = <({String name, String url, int size})>[]; + for (final item in assets) { + if (item is! Map) continue; + final name = (item['name'] as String? ?? '').trim(); + final url = (item['browser_download_url'] as String? ?? '').trim(); + final size = (item['size'] as num?)?.toInt() ?? 0; + if (name.toLowerCase().endsWith('.apk') && url.isNotEmpty) { + apkAssets.add((name: name, url: url, size: size)); + } + } + + if (apkAssets.isEmpty) { + return (fallbackUrl, ''); + } + + ({String name, String url, int size})? matched; + for (final abi in supportedAbis) { + final lowerAbi = abi.toLowerCase(); + for (final asset in apkAssets) { + if (asset.name.toLowerCase().contains(lowerAbi)) { + matched = asset; + break; + } + } + if (matched != null) break; + } + + matched ??= apkAssets + .where((a) => a.name.toLowerCase().contains('universal')) + .firstOrNull; + matched ??= apkAssets.first; + + final sizeText = matched.size > 0 + ? '${(matched.size / (1024 * 1024)).toStringAsFixed(2)} MB' + : ''; + return (matched.url, sizeText); + } + + @visibleForTesting + static bool isNewerVersion(String remoteVersion, String currentVersion) { + final remoteParts = _parseVersionParts(remoteVersion); + final currentParts = _parseVersionParts(currentVersion); + if (remoteParts.isEmpty) return false; + + final maxLen = + remoteParts.length > currentParts.length ? remoteParts.length : currentParts.length; + for (var i = 0; i < maxLen; i++) { + final r = i < remoteParts.length ? remoteParts[i] : 0; + final c = i < currentParts.length ? currentParts[i] : 0; + if (r != c) return r > c; + } + return false; + } + + @visibleForTesting + static int parseVersionCode(String versionName) { + final parts = _parseVersionParts(versionName); + if (parts.isEmpty) return 0; + final major = parts.isNotEmpty ? parts[0] : 0; + final minor = parts.length > 1 ? parts[1] : 0; + final patch = parts.length > 2 ? parts[2] : 0; + return major * 10000 + minor * 100 + patch; + } + + static List _parseVersionParts(String version) { + final cleaned = version.trim().replaceFirst(RegExp(r'^[vV]'), ''); + if (cleaned.isEmpty) return const []; + return cleaned.split('.').map((seg) { + final match = RegExp(r'^\d+').firstMatch(seg); + return match != null ? int.parse(match.group(0)!) : 0; + }).toList(); + } +} diff --git a/lib/views/main_view.dart b/lib/views/main_view.dart index 34d1862..5a278fa 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -7,6 +7,7 @@ import 'package:code_editor/providers/project_provider.dart'; import 'package:code_editor/providers/run_provider.dart'; import 'package:code_editor/providers/tab_provider.dart'; import 'package:code_editor/providers/terminal_provider.dart'; +import 'package:code_editor/services/app_update_service.dart'; import 'package:code_editor/services/distro_manager.dart'; import 'package:code_editor/services/permission_service.dart'; import 'package:code_editor/services/toolchain_service.dart'; @@ -82,13 +83,15 @@ class _MainViewState extends State { LspConfigService.instance.addListener(_handleLspConfigChanged); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { + final settings = context.read(); InternalEngineService.instance.ensureEngineReady(context); LspConfigService.instance.loadConfigs(); DistroManager().detectAndApplyRuntime( context: context, - settings: context.read(), + settings: settings, showToast: true, ); + AppUpdateService.instance.checkAutoUpdate(context, settings); } }); } diff --git a/lib/views/settings_view.dart b/lib/views/settings_view.dart index d40637d..1971443 100644 --- a/lib/views/settings_view.dart +++ b/lib/views/settings_view.dart @@ -5,6 +5,7 @@ import 'package:code_editor/models/virtual_keyboard_config.dart'; import 'package:code_editor/providers/settings_provider.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../services/app_update_service.dart'; import '../services/distro_manager.dart'; import '../services/internal_engine_service.dart'; import '../widgets/color_palette_dialog.dart'; @@ -98,6 +99,16 @@ class SettingsView extends StatelessWidget { // ============================== _buildSectionHeader(context, l10n.languageSection), _buildLanguageTile(context, provider, l10n), + + const Divider(height: 32, indent: 16, endIndent: 16), + + // ============================== + // 7. 关于与更新分组 (About & Updates) + // ============================== + _buildSectionHeader(context, l10n.aboutAndUpdatesSection), + _buildAppVersionTile(context, l10n), + _buildAutoCheckUpdateTile(context, provider, l10n), + _buildCheckUpdateTile(context, provider, l10n), ], ), ); @@ -1332,4 +1343,88 @@ class SettingsView extends StatelessWidget { } } } + + Widget _buildAppVersionTile(BuildContext context, AppLocalizations l10n) { + final theme = Theme.of(context); + return FutureBuilder( + future: AppUpdateService.instance.getCurrentAppVersion(), + builder: (context, snapshot) { + final version = snapshot.data ?? AppUpdateService.fallbackVersionName; + return ListTile( + leading: Icon(Icons.info_outline, color: theme.colorScheme.primary), + title: Text(l10n.appVersionLabel), + trailing: Text( + 'v$version', + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ); + }, + ); + } + + Widget _buildAutoCheckUpdateTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + return SwitchListTile( + secondary: Icon(Icons.autorenew, color: theme.colorScheme.primary), + title: Text(l10n.autoCheckUpdates), + subtitle: Text(l10n.autoCheckUpdatesSubtitle), + value: provider.autoCheckUpdate, + onChanged: (value) => provider.setAutoCheckUpdate(value), + ); + } + + Widget _buildCheckUpdateTile( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) { + final theme = Theme.of(context); + return ListTile( + leading: Icon(Icons.system_update_outlined, color: theme.colorScheme.primary), + title: Text(l10n.checkForUpdates), + trailing: const Icon(Icons.chevron_right), + onTap: () => _handleManualCheckUpdate(context, provider, l10n), + ); + } + + Future _handleManualCheckUpdate( + BuildContext context, + SettingsProvider provider, + AppLocalizations l10n, + ) async { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(l10n.checkingUpdates), + duration: const Duration(seconds: 2), + ), + ); + try { + final info = await AppUpdateService.instance.checkUpdate(); + if (!context.mounted) return; + ScaffoldMessenger.of(context).hideCurrentSnackBar(); + if (info.hasUpdate) { + await AppUpdateService.instance.showUpdateDialog( + context, + info, + settings: provider, + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(l10n.alreadyLatestVersion)), + ); + } + } catch (_) { + if (!context.mounted) return; + ScaffoldMessenger.of(context).hideCurrentSnackBar(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(l10n.updateCheckFailed)), + ); + } + } } diff --git a/pubspec.yaml b/pubspec.yaml index fad17a2..f086c29 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: code_editor description: "A new Flutter project." publish_to: 'none' -version: 1.0.2+3 +version: 1.0.3+4 environment: sdk: ^3.9.2 diff --git a/test/app_update_service_test.dart b/test/app_update_service_test.dart new file mode 100644 index 0000000..077d4c6 --- /dev/null +++ b/test/app_update_service_test.dart @@ -0,0 +1,75 @@ +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/services/app_update_service.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('AppUpdateService', () { + test('isNewerVersion compares semantic versions accurately', () { + expect(AppUpdateService.isNewerVersion('1.0.4', '1.0.3'), isTrue); + expect(AppUpdateService.isNewerVersion('v1.1.0', '1.0.3'), isTrue); + expect(AppUpdateService.isNewerVersion('1.0.3', '1.0.3'), isFalse); + expect(AppUpdateService.isNewerVersion('1.0.2', '1.0.3'), isFalse); + expect(AppUpdateService.isNewerVersion('v1.0.10', '1.0.9'), isTrue); + }); + + test('parseVersionCode produces monotonic integer codes', () { + expect(AppUpdateService.parseVersionCode('v1.0.3'), 10003); + expect(AppUpdateService.parseVersionCode('1.2.4'), 10204); + expect(AppUpdateService.parseVersionCode('1.0.10'), 10010); + }); + + test('parseReleaseJson selects universal or matching ABI APK asset', () { + const sampleJson = ''' + { + "tag_name": "v1.0.4", + "name": "LN Code Editor v1.0.4", + "body": "- Fix something\\n- Improve speed", + "html_url": "https://gitea.lzxnone.cloud/lzxnone/LN-Code-Editor/releases/tag/v1.0.4", + "assets": [ + { + "name": "LN-Code-Editor-v1.0.4-universal.apk", + "size": 104857600, + "browser_download_url": "https://gitea.lzxnone.cloud/attachments/univ" + }, + { + "name": "LN-Code-Editor-v1.0.4-arm64-v8a.apk", + "size": 83886080, + "browser_download_url": "https://gitea.lzxnone.cloud/attachments/arm64" + } + ] + } + '''; + + final arm64Info = AppUpdateService.parseReleaseJson( + sampleJson, + currentVersion: '1.0.3', + supportedAbis: ['arm64-v8a', 'armeabi-v7a'], + ); + expect(arm64Info.hasUpdate, isTrue); + expect(arm64Info.versionName, '1.0.4'); + expect(arm64Info.versionCode, 10004); + expect(arm64Info.downloadUrl, 'https://gitea.lzxnone.cloud/attachments/arm64'); + expect(arm64Info.apkSize, '80.00 MB'); + + final fallbackUniv = AppUpdateService.parseReleaseJson( + sampleJson, + currentVersion: '1.0.4', + supportedAbis: [], + ); + expect(fallbackUniv.hasUpdate, isFalse); + expect(fallbackUniv.downloadUrl, 'https://gitea.lzxnone.cloud/attachments/univ'); + expect(fallbackUniv.apkSize, '100.00 MB'); + }); + + test('update l10n keys exist in zh and en', () { + final zh = lookupAppLocalizations(const Locale('zh')); + final en = lookupAppLocalizations(const Locale('en')); + + expect(zh.aboutAndUpdatesSection, '关于与更新'); + expect(en.aboutAndUpdatesSection, 'About & Updates'); + expect(zh.newVersionAvailableTitle('V1.0.4'), '发现新版本 V1.0.4'); + expect(en.newVersionAvailableTitle('V1.0.4'), 'New Version V1.0.4'); + }); + }); +}