This commit is contained in:
LZX committed 2026-09-15 00:50:53 +08:00
1 parent cce34e7960
commit b49e096355
56 files changed
+8320 -273

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ plugins {
android {
namespace = "com.example.code_editor"
compileSdk = flutter.compileSdkVersion
compileSdk = 37
ndkVersion = "28.2.13676358"
compileOptions {
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
-----BEGIN CERTIFICATE-----MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UEAwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQswCQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUNDVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCbqau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoYHtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWoG2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpAlHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhrIA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eHk6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/474KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMOm3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpacXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPluUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYIKwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmlsZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsGAQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeTVfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIGCCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUAcgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEAQwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQAcgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAAQwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUAczAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2MuaHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRtaW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1UdDwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEFBQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdpD70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gUJyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+mAM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepDvV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlmstn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5hI6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szAh1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xFd3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2HpPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7-----END CERTIFICATE----------BEGIN CERTIFICATE-----MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBGTk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgfBBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAzWHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxFtBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdICIfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DULmbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peSMKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2ZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMetUqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+HYJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDDnFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1RXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYMLVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2NJpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jmfZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wokRqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYvuu8wd+RU4riEmViAqhOLUTpPSPaLtrM=-----END CERTIFICATE----------BEGIN CERTIFICATE-----MIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQswCQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgwFgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1SQ00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5MzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtLine truncated
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+129 -3
View File
@@ -164,7 +164,7 @@
"terminalInputHint": "Enter command...",
"sendCommandTooltip": "Send Command",
"importNewSystem": "Import New System",
"importBuiltinAlpine": "Import from App (Alpine)",
"importFromApp": "Import from App",
"importExternalTarGz": "Import from External (.tar.gz)",
"selectSystemDefaultPrompt": "Select a system as default; new terminals will start in this system:",
"noSystemsPrompt": "No systems available. Tap \"+\" at top right to import",
@@ -205,6 +205,27 @@
}
},
"permanentDelete": "Permanently Delete",
"distroManagementTitle": "System Management",
"installedStatus": "Installed",
"notInstalledStatus": "Not Installed",
"downloadingStatus": "Downloading",
"downloadAction": "Download",
"installAction": "Install",
"builtinTag": "Built-in",
"cancelDownloadAction": "Cancel Download",
"cancelDownloadConfirmTitle": "Cancel Download",
"cancelDownloadConfirmMessage": "Are you sure you want to cancel the downloading system package? The downloaded parts will be discarded.",
"deletingSystemProgress": "Deleting system and cleaning storage, please wait...",
"cannotDeleteBuiltinSystem": "Built-in system is protected and cannot be deleted",
"recommendedTag": "Recommended",
"downloadFailed": "Download failed: {error}",
"@downloadFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"deleteSystemSuccess": "System \"{name}\" and associated sessions deleted",
"@deleteSystemSuccess": {
"placeholders": {
@@ -213,6 +234,33 @@
}
}
},
"deletePackageConfirmTitle": "Confirm Delete Package",
"deletePackageConfirmMessage": "Are you sure you want to delete the package for \"{name}\"? You can download it again at any time.",
"@deletePackageConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deletingPackageProgress": "Deleting package, please wait...",
"deletePackageSuccess": "Deleted \"{name}\" package",
"@deletePackageSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deletePackageTooltip": "Delete downloaded system package",
"importSystemInstanceTitle": "Create {name} System Instance",
"@importSystemInstanceTitle": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSystemTooltip": "Permanently delete this system (High risk)",
"preparingInitialization": "Preparing initialization...",
"cancellingAndCleaning": "Cancelling and cleaning leftover directory...",
@@ -481,7 +529,7 @@
"shellCommandEmptyError": "Please enter command",
"taskDescOptional": "Description (Optional)",
"taskDescHint": "Briefly describe the task purpose",
"clearBeforeRun": "Clear Screen (clear)",
"clearBeforeRun": "Clear Screen",
"clearBeforeRunSubtitle": "Clear terminal output before executing task",
"runTasksUpdated": "Run tasks configuration updated",
"detectCompletedMessage": "Detection completed, found {count} tasks",
@@ -520,5 +568,83 @@
}
},
"unsavedTaskChangesTitle": "Unsaved Task Changes",
"unsavedTaskChangesMessage": "The task has been modified. Do you want to discard unsaved changes and leave?"
"unsavedTaskChangesMessage": "The task has been modified. Do you want to discard unsaved changes and leave?",
"downloadSection": "Download",
"downloadSource": "Download Source",
"selectDownloadSource": "Select Download Source",
"mirrorName": "{mirror, select, tsinghua{Tsinghua TUNA Mirror (Recommended)} bfsu{BFSU Open Source Mirror} iscas{ISCAS Open Source Mirror} official{LinuxContainers Official Mirror} other{{mirror}}}",
"@mirrorName": {
"placeholders": {
"mirror": {
"type": "String"
}
}
},
"unnamedTask": "Unnamed Task",
"shellCommandHelperText": "Supports single-line commands (e.g. make) or multi-line Shell scripts (packaged and executed automatically)",
"detectedTaskCmakeBuildRunDesc": "Configure, build, and try launching the target executable",
"detectedTaskCmakeBuildDesc": "Only execute cmake generation and build",
"detectedTaskCmakeCleanDesc": "Clean build cache directory",
"detectedTaskGradleRunDesc": "Execute application main entrypoint",
"detectedTaskGradleAssembleDesc": "Build debug output package",
"detectedTaskGradleBuildDesc": "Execute full build and tests",
"detectedTaskMakeDefaultDesc": "Execute default Makefile build target",
"detectedTaskNpmStartDesc": "Start Node service or frontend development environment",
"detectedTaskNpmTestDesc": "Execute npm test suite",
"detectedTaskCargoRunDesc": "Compile and run Rust project",
"detectedTaskCargoBuildDesc": "Compile Rust project only",
"detectedTaskDartRunDesc": "Launch Dart application",
"detectedTaskSinglePythonDesc": "Run current Python script",
"detectedTaskSingleCDesc": "Compile and execute current C source file",
"detectedTaskSingleCppDesc": "Compile and execute current C++ source file",
"detectedTaskSingleShDesc": "Run current Shell script",
"detectedTaskSingleDartDesc": "Run current Dart file",
"detectedTaskSingleGoDesc": "Run current Go source file",
"detectedTaskSingleRustDesc": "Compile and execute current Rust source file",
"detectedTaskSingleJsDesc": "Run current JavaScript script",
"missingDistroTitle": "System Environment Not Ready",
"noDistroAvailableContent": "No available Linux execution environment detected.\n\nProject tasks need to run inside a Linux container. Please install or download a Linux system first (e.g. Ubuntu or Alpine).",
"distroNotInstalledContent": "System \"{distro}\" is not installed or has been removed.\n\nPlease install it in System Management or select another available system.",
"@distroNotInstalledContent": {
"placeholders": {
"distro": {
"type": "String"
}
}
},
"openFromApp": "Open from App",
"openFromExternal": "Open from External",
"projectsTitle": "Projects",
"newProject": "New Project",
"newProjectTitle": "New Project",
"projectNameHint": "Enter project name",
"renameProject": "Rename Project",
"deleteProject": "Delete Project",
"deleteProjectConfirmMessage": "Are you sure you want to delete project \"{name}\"? This action cannot be undone.",
"@deleteProjectConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"projectAlreadyExists": "A project with this name already exists",
"noProjects": "No projects yet, click top right to create one",
"projectCreated": "Project created successfully",
"projectRenamed": "Project renamed successfully",
"projectDeleted": "Project deleted",
"importFromExternal": "Import from External",
"confirmProjectNameTitle": "Confirm Project Name",
"importingProject": "Importing project...",
"projectImported": "Project imported successfully",
"importProjectFailed": "Failed to import project: {error}",
"@importProjectFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"unsupportedProjectArchiveFormat": "Unsupported file format. Only archive files (.zip, .tar.gz, .tar.xz, .tar, etc.) are supported",
"unsupportedDistroArchiveFormat": "Unsupported file format. Only system archives (.tar.gz, .tar.xz, .tar) are supported"
}
+424 -4
View File
@@ -950,11 +950,11 @@ abstract class AppLocalizations {
/// **'导入新系统'**
String get importNewSystem;
/// No description provided for @importBuiltinAlpine.
/// No description provided for @importFromApp.
///
/// In zh, this message translates to:
/// **'从软件中导入 (Alpine)'**
String get importBuiltinAlpine;
/// **'从软件中导入'**
String get importFromApp;
/// No description provided for @importExternalTarGz.
///
@@ -1028,12 +1028,132 @@ abstract class AppLocalizations {
/// **'彻底删除'**
String get permanentDelete;
/// No description provided for @distroManagementTitle.
///
/// In zh, this message translates to:
/// **'系统管理'**
String get distroManagementTitle;
/// No description provided for @installedStatus.
///
/// In zh, this message translates to:
/// **'已安装'**
String get installedStatus;
/// No description provided for @notInstalledStatus.
///
/// In zh, this message translates to:
/// **'未安装'**
String get notInstalledStatus;
/// No description provided for @downloadingStatus.
///
/// In zh, this message translates to:
/// **'下载中'**
String get downloadingStatus;
/// No description provided for @downloadAction.
///
/// In zh, this message translates to:
/// **'下载'**
String get downloadAction;
/// No description provided for @installAction.
///
/// In zh, this message translates to:
/// **'安装'**
String get installAction;
/// No description provided for @builtinTag.
///
/// In zh, this message translates to:
/// **'内置'**
String get builtinTag;
/// No description provided for @cancelDownloadAction.
///
/// In zh, this message translates to:
/// **'取消下载'**
String get cancelDownloadAction;
/// No description provided for @cancelDownloadConfirmTitle.
///
/// In zh, this message translates to:
/// **'取消下载'**
String get cancelDownloadConfirmTitle;
/// No description provided for @cancelDownloadConfirmMessage.
///
/// In zh, this message translates to:
/// **'确定要取消正在下载的系统资源吗?已下载的部分将被清除。'**
String get cancelDownloadConfirmMessage;
/// No description provided for @deletingSystemProgress.
///
/// In zh, this message translates to:
/// **'正在删除系统并清理数据,请稍候...'**
String get deletingSystemProgress;
/// No description provided for @cannotDeleteBuiltinSystem.
///
/// In zh, this message translates to:
/// **'内置系统受到保护,无法删除'**
String get cannotDeleteBuiltinSystem;
/// No description provided for @recommendedTag.
///
/// In zh, this message translates to:
/// **'推荐'**
String get recommendedTag;
/// No description provided for @downloadFailed.
///
/// In zh, this message translates to:
/// **'下载失败: {error}'**
String downloadFailed(String error);
/// No description provided for @deleteSystemSuccess.
///
/// In zh, this message translates to:
/// **'已彻底删除系统 \"{name}\" 及关联会话'**
String deleteSystemSuccess(String name);
/// No description provided for @deletePackageConfirmTitle.
///
/// In zh, this message translates to:
/// **'确认删除安装包'**
String get deletePackageConfirmTitle;
/// No description provided for @deletePackageConfirmMessage.
///
/// In zh, this message translates to:
/// **'确定要删除 \"{name}\" 的系统安装包吗?删除后可随时重新下载。'**
String deletePackageConfirmMessage(String name);
/// No description provided for @deletingPackageProgress.
///
/// In zh, this message translates to:
/// **'正在删除安装包,请稍候...'**
String get deletingPackageProgress;
/// No description provided for @deletePackageSuccess.
///
/// In zh, this message translates to:
/// **'已删除 \"{name}\" 安装包'**
String deletePackageSuccess(String name);
/// No description provided for @deletePackageTooltip.
///
/// In zh, this message translates to:
/// **'删除已下载的系统安装包'**
String get deletePackageTooltip;
/// No description provided for @importSystemInstanceTitle.
///
/// In zh, this message translates to:
/// **'创建 {name} 系统实例'**
String importSystemInstanceTitle(String name);
/// No description provided for @deleteSystemTooltip.
///
/// In zh, this message translates to:
@@ -1751,7 +1871,7 @@ abstract class AppLocalizations {
/// No description provided for @clearBeforeRun.
///
/// In zh, this message translates to:
/// **'执行前清屏 (clear)'**
/// **'执行前清屏'**
String get clearBeforeRun;
/// No description provided for @clearBeforeRunSubtitle.
@@ -1819,6 +1939,306 @@ abstract class AppLocalizations {
/// In zh, this message translates to:
/// **'当前任务内容已被修改,是否放弃未保存的修改并返回?'**
String get unsavedTaskChangesMessage;
/// No description provided for @downloadSection.
///
/// In zh, this message translates to:
/// **'下载'**
String get downloadSection;
/// No description provided for @downloadSource.
///
/// In zh, this message translates to:
/// **'下载源'**
String get downloadSource;
/// No description provided for @selectDownloadSource.
///
/// In zh, this message translates to:
/// **'选择下载源'**
String get selectDownloadSource;
/// No description provided for @mirrorName.
///
/// In zh, this message translates to:
/// **'{mirror, select, tsinghua{清华大学开源软件镜像站 (推荐)} bfsu{北京外国语大学开源软件镜像站} iscas{中国科学院软件研究所开源镜像站} official{LinuxContainers 官方镜像源} other{{mirror}}}'**
String mirrorName(String mirror);
/// No description provided for @unnamedTask.
///
/// In zh, this message translates to:
/// **'未命名任务'**
String get unnamedTask;
/// No description provided for @shellCommandHelperText.
///
/// In zh, this message translates to:
/// **'支持单行指令(如 make)或多行 Shell 脚本(自动封装执行)'**
String get shellCommandHelperText;
/// No description provided for @detectedTaskCmakeBuildRunDesc.
///
/// In zh, this message translates to:
/// **'配置、编译并尝试启动生成的目标程序'**
String get detectedTaskCmakeBuildRunDesc;
/// No description provided for @detectedTaskCmakeBuildDesc.
///
/// In zh, this message translates to:
/// **'仅执行 cmake 生成与构建'**
String get detectedTaskCmakeBuildDesc;
/// No description provided for @detectedTaskCmakeCleanDesc.
///
/// In zh, this message translates to:
/// **'清理构建缓存目录'**
String get detectedTaskCmakeCleanDesc;
/// No description provided for @detectedTaskGradleRunDesc.
///
/// In zh, this message translates to:
/// **'执行应用程序主入口'**
String get detectedTaskGradleRunDesc;
/// No description provided for @detectedTaskGradleAssembleDesc.
///
/// In zh, this message translates to:
/// **'构建调试输出包'**
String get detectedTaskGradleAssembleDesc;
/// No description provided for @detectedTaskGradleBuildDesc.
///
/// In zh, this message translates to:
/// **'执行完整构建与测试'**
String get detectedTaskGradleBuildDesc;
/// No description provided for @detectedTaskMakeDefaultDesc.
///
/// In zh, this message translates to:
/// **'执行默认 Makefile 构建目标'**
String get detectedTaskMakeDefaultDesc;
/// No description provided for @detectedTaskNpmStartDesc.
///
/// In zh, this message translates to:
/// **'启动 Node 服务或前端开发环境'**
String get detectedTaskNpmStartDesc;
/// No description provided for @detectedTaskNpmTestDesc.
///
/// In zh, this message translates to:
/// **'执行 npm test 测试套件'**
String get detectedTaskNpmTestDesc;
/// No description provided for @detectedTaskCargoRunDesc.
///
/// In zh, this message translates to:
/// **'编译并运行 Rust 项目'**
String get detectedTaskCargoRunDesc;
/// No description provided for @detectedTaskCargoBuildDesc.
///
/// In zh, this message translates to:
/// **'仅编译 Rust 项目'**
String get detectedTaskCargoBuildDesc;
/// No description provided for @detectedTaskDartRunDesc.
///
/// In zh, this message translates to:
/// **'启动 Dart 应用'**
String get detectedTaskDartRunDesc;
/// No description provided for @detectedTaskSinglePythonDesc.
///
/// In zh, this message translates to:
/// **'运行当前 Python 脚本'**
String get detectedTaskSinglePythonDesc;
/// No description provided for @detectedTaskSingleCDesc.
///
/// In zh, this message translates to:
/// **'编译并执行当前 C 源文件'**
String get detectedTaskSingleCDesc;
/// No description provided for @detectedTaskSingleCppDesc.
///
/// In zh, this message translates to:
/// **'编译并执行当前 C++ 源文件'**
String get detectedTaskSingleCppDesc;
/// No description provided for @detectedTaskSingleShDesc.
///
/// In zh, this message translates to:
/// **'运行当前 Shell 脚本'**
String get detectedTaskSingleShDesc;
/// No description provided for @detectedTaskSingleDartDesc.
///
/// In zh, this message translates to:
/// **'运行当前 Dart 文件'**
String get detectedTaskSingleDartDesc;
/// No description provided for @detectedTaskSingleGoDesc.
///
/// In zh, this message translates to:
/// **'运行当前 Go 源文件'**
String get detectedTaskSingleGoDesc;
/// No description provided for @detectedTaskSingleRustDesc.
///
/// In zh, this message translates to:
/// **'编译并执行当前 Rust 源文件'**
String get detectedTaskSingleRustDesc;
/// No description provided for @detectedTaskSingleJsDesc.
///
/// In zh, this message translates to:
/// **'运行当前 JS 脚本'**
String get detectedTaskSingleJsDesc;
/// No description provided for @missingDistroTitle.
///
/// In zh, this message translates to:
/// **'系统环境未就绪'**
String get missingDistroTitle;
/// No description provided for @noDistroAvailableContent.
///
/// In zh, this message translates to:
/// **'未检测到可用的 Linux 执行环境。\n\n工程任务需要在 Linux 容器环境中运行。请先安装或下载 Linux 系统(如 Ubuntu 或 Alpine)。'**
String get noDistroAvailableContent;
/// No description provided for @distroNotInstalledContent.
///
/// In zh, this message translates to:
/// **'系统 \"{distro}\" 尚未安装或已被清理。\n\n请在系统管理中安装该系统,或选择其他已就绪的系统。'**
String distroNotInstalledContent(String distro);
/// No description provided for @openFromApp.
///
/// In zh, this message translates to:
/// **'从软件内打开'**
String get openFromApp;
/// No description provided for @openFromExternal.
///
/// In zh, this message translates to:
/// **'从外部打开'**
String get openFromExternal;
/// No description provided for @projectsTitle.
///
/// In zh, this message translates to:
/// **'项目'**
String get projectsTitle;
/// No description provided for @newProject.
///
/// In zh, this message translates to:
/// **'新建项目'**
String get newProject;
/// No description provided for @newProjectTitle.
///
/// In zh, this message translates to:
/// **'新建项目'**
String get newProjectTitle;
/// No description provided for @projectNameHint.
///
/// In zh, this message translates to:
/// **'请输入项目名称'**
String get projectNameHint;
/// No description provided for @renameProject.
///
/// In zh, this message translates to:
/// **'重命名项目'**
String get renameProject;
/// No description provided for @deleteProject.
///
/// In zh, this message translates to:
/// **'删除项目'**
String get deleteProject;
/// No description provided for @deleteProjectConfirmMessage.
///
/// In zh, this message translates to:
/// **'确定要删除项目 \"{name}\" 吗?此操作不可逆。'**
String deleteProjectConfirmMessage(String name);
/// No description provided for @projectAlreadyExists.
///
/// In zh, this message translates to:
/// **'已存在同名项目'**
String get projectAlreadyExists;
/// No description provided for @noProjects.
///
/// In zh, this message translates to:
/// **'暂无项目,点击右上角新建项目'**
String get noProjects;
/// No description provided for @projectCreated.
///
/// In zh, this message translates to:
/// **'项目创建成功'**
String get projectCreated;
/// No description provided for @projectRenamed.
///
/// In zh, this message translates to:
/// **'项目重命名成功'**
String get projectRenamed;
/// No description provided for @projectDeleted.
///
/// In zh, this message translates to:
/// **'项目已删除'**
String get projectDeleted;
/// No description provided for @importFromExternal.
///
/// In zh, this message translates to:
/// **'从外部导入'**
String get importFromExternal;
/// No description provided for @confirmProjectNameTitle.
///
/// In zh, this message translates to:
/// **'确认项目名称'**
String get confirmProjectNameTitle;
/// No description provided for @importingProject.
///
/// In zh, this message translates to:
/// **'正在导入项目...'**
String get importingProject;
/// No description provided for @projectImported.
///
/// In zh, this message translates to:
/// **'项目导入成功'**
String get projectImported;
/// No description provided for @importProjectFailed.
///
/// In zh, this message translates to:
/// **'导入项目失败: {error}'**
String importProjectFailed(String error);
/// No description provided for @unsupportedProjectArchiveFormat.
///
/// In zh, this message translates to:
/// **'不支持的文件格式,仅支持压缩包格式 (.zip, .tar.gz, .tar.xz, .tar 等)'**
String get unsupportedProjectArchiveFormat;
/// No description provided for @unsupportedDistroArchiveFormat.
///
/// In zh, this message translates to:
/// **'不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)'**
String get unsupportedDistroArchiveFormat;
}
class _AppLocalizationsDelegate
+249 -2
View File
@@ -486,7 +486,7 @@ class AppLocalizationsEn extends AppLocalizations {
String get importNewSystem => 'Import New System';
@override
String get importBuiltinAlpine => 'Import from App (Alpine)';
String get importFromApp => 'Import from App';
@override
String get importExternalTarGz => 'Import from External (.tar.gz)';
@@ -534,11 +534,82 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get permanentDelete => 'Permanently Delete';
@override
String get distroManagementTitle => 'System Management';
@override
String get installedStatus => 'Installed';
@override
String get notInstalledStatus => 'Not Installed';
@override
String get downloadingStatus => 'Downloading';
@override
String get downloadAction => 'Download';
@override
String get installAction => 'Install';
@override
String get builtinTag => 'Built-in';
@override
String get cancelDownloadAction => 'Cancel Download';
@override
String get cancelDownloadConfirmTitle => 'Cancel Download';
@override
String get cancelDownloadConfirmMessage =>
'Are you sure you want to cancel the downloading system package? The downloaded parts will be discarded.';
@override
String get deletingSystemProgress =>
'Deleting system and cleaning storage, please wait...';
@override
String get cannotDeleteBuiltinSystem =>
'Built-in system is protected and cannot be deleted';
@override
String get recommendedTag => 'Recommended';
@override
String downloadFailed(String error) {
return 'Download failed: $error';
}
@override
String deleteSystemSuccess(String name) {
return 'System \"$name\" and associated sessions deleted';
}
@override
String get deletePackageConfirmTitle => 'Confirm Delete Package';
@override
String deletePackageConfirmMessage(String name) {
return 'Are you sure you want to delete the package for \"$name\"? You can download it again at any time.';
}
@override
String get deletingPackageProgress => 'Deleting package, please wait...';
@override
String deletePackageSuccess(String name) {
return 'Deleted \"$name\" package';
}
@override
String get deletePackageTooltip => 'Delete downloaded system package';
@override
String importSystemInstanceTitle(String name) {
return 'Create $name System Instance';
}
@override
String get deleteSystemTooltip =>
'Permanently delete this system (High risk)';
@@ -1053,7 +1124,7 @@ class AppLocalizationsEn extends AppLocalizations {
String get taskDescHint => 'Briefly describe the task purpose';
@override
String get clearBeforeRun => 'Clear Screen (clear)';
String get clearBeforeRun => 'Clear Screen';
@override
String get clearBeforeRunSubtitle =>
@@ -1097,4 +1168,180 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get unsavedTaskChangesMessage =>
'The task has been modified. Do you want to discard unsaved changes and leave?';
@override
String get downloadSection => 'Download';
@override
String get downloadSource => 'Download Source';
@override
String get selectDownloadSource => 'Select Download Source';
@override
String mirrorName(String mirror) {
String _temp0 = intl.Intl.selectLogic(mirror, {
'tsinghua': 'Tsinghua TUNA Mirror (Recommended)',
'bfsu': 'BFSU Open Source Mirror',
'iscas': 'ISCAS Open Source Mirror',
'official': 'LinuxContainers Official Mirror',
'other': '$mirror',
});
return '$_temp0';
}
@override
String get unnamedTask => 'Unnamed Task';
@override
String get shellCommandHelperText =>
'Supports single-line commands (e.g. make) or multi-line Shell scripts (packaged and executed automatically)';
@override
String get detectedTaskCmakeBuildRunDesc =>
'Configure, build, and try launching the target executable';
@override
String get detectedTaskCmakeBuildDesc =>
'Only execute cmake generation and build';
@override
String get detectedTaskCmakeCleanDesc => 'Clean build cache directory';
@override
String get detectedTaskGradleRunDesc => 'Execute application main entrypoint';
@override
String get detectedTaskGradleAssembleDesc => 'Build debug output package';
@override
String get detectedTaskGradleBuildDesc => 'Execute full build and tests';
@override
String get detectedTaskMakeDefaultDesc =>
'Execute default Makefile build target';
@override
String get detectedTaskNpmStartDesc =>
'Start Node service or frontend development environment';
@override
String get detectedTaskNpmTestDesc => 'Execute npm test suite';
@override
String get detectedTaskCargoRunDesc => 'Compile and run Rust project';
@override
String get detectedTaskCargoBuildDesc => 'Compile Rust project only';
@override
String get detectedTaskDartRunDesc => 'Launch Dart application';
@override
String get detectedTaskSinglePythonDesc => 'Run current Python script';
@override
String get detectedTaskSingleCDesc =>
'Compile and execute current C source file';
@override
String get detectedTaskSingleCppDesc =>
'Compile and execute current C++ source file';
@override
String get detectedTaskSingleShDesc => 'Run current Shell script';
@override
String get detectedTaskSingleDartDesc => 'Run current Dart file';
@override
String get detectedTaskSingleGoDesc => 'Run current Go source file';
@override
String get detectedTaskSingleRustDesc =>
'Compile and execute current Rust source file';
@override
String get detectedTaskSingleJsDesc => 'Run current JavaScript script';
@override
String get missingDistroTitle => 'System Environment Not Ready';
@override
String get noDistroAvailableContent =>
'No available Linux execution environment detected.\n\nProject tasks need to run inside a Linux container. Please install or download a Linux system first (e.g. Ubuntu or Alpine).';
@override
String distroNotInstalledContent(String distro) {
return 'System \"$distro\" is not installed or has been removed.\n\nPlease install it in System Management or select another available system.';
}
@override
String get openFromApp => 'Open from App';
@override
String get openFromExternal => 'Open from External';
@override
String get projectsTitle => 'Projects';
@override
String get newProject => 'New Project';
@override
String get newProjectTitle => 'New Project';
@override
String get projectNameHint => 'Enter project name';
@override
String get renameProject => 'Rename Project';
@override
String get deleteProject => 'Delete Project';
@override
String deleteProjectConfirmMessage(String name) {
return 'Are you sure you want to delete project \"$name\"? This action cannot be undone.';
}
@override
String get projectAlreadyExists => 'A project with this name already exists';
@override
String get noProjects => 'No projects yet, click top right to create one';
@override
String get projectCreated => 'Project created successfully';
@override
String get projectRenamed => 'Project renamed successfully';
@override
String get projectDeleted => 'Project deleted';
@override
String get importFromExternal => 'Import from External';
@override
String get confirmProjectNameTitle => 'Confirm Project Name';
@override
String get importingProject => 'Importing project...';
@override
String get projectImported => 'Project imported successfully';
@override
String importProjectFailed(String error) {
return 'Failed to import project: $error';
}
@override
String get unsupportedProjectArchiveFormat =>
'Unsupported file format. Only archive files (.zip, .tar.gz, .tar.xz, .tar, etc.) are supported';
@override
String get unsupportedDistroArchiveFormat =>
'Unsupported file format. Only system archives (.tar.gz, .tar.xz, .tar) are supported';
}
+238 -2
View File
@@ -477,7 +477,7 @@ class AppLocalizationsZh extends AppLocalizations {
String get importNewSystem => '导入新系统';
@override
String get importBuiltinAlpine => '从软件中导入 (Alpine)';
String get importFromApp => '从软件中导入';
@override
String get importExternalTarGz => '从外部导入 (.tar.gz)';
@@ -523,11 +523,79 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get permanentDelete => '彻底删除';
@override
String get distroManagementTitle => '系统管理';
@override
String get installedStatus => '已安装';
@override
String get notInstalledStatus => '未安装';
@override
String get downloadingStatus => '下载中';
@override
String get downloadAction => '下载';
@override
String get installAction => '安装';
@override
String get builtinTag => '内置';
@override
String get cancelDownloadAction => '取消下载';
@override
String get cancelDownloadConfirmTitle => '取消下载';
@override
String get cancelDownloadConfirmMessage => '确定要取消正在下载的系统资源吗?已下载的部分将被清除。';
@override
String get deletingSystemProgress => '正在删除系统并清理数据,请稍候...';
@override
String get cannotDeleteBuiltinSystem => '内置系统受到保护,无法删除';
@override
String get recommendedTag => '推荐';
@override
String downloadFailed(String error) {
return '下载失败: $error';
}
@override
String deleteSystemSuccess(String name) {
return '已彻底删除系统 \"$name\" 及关联会话';
}
@override
String get deletePackageConfirmTitle => '确认删除安装包';
@override
String deletePackageConfirmMessage(String name) {
return '确定要删除 \"$name\" 的系统安装包吗?删除后可随时重新下载。';
}
@override
String get deletingPackageProgress => '正在删除安装包,请稍候...';
@override
String deletePackageSuccess(String name) {
return '已删除 \"$name\" 安装包';
}
@override
String get deletePackageTooltip => '删除已下载的系统安装包';
@override
String importSystemInstanceTitle(String name) {
return '创建 $name 系统实例';
}
@override
String get deleteSystemTooltip => '彻底删除该系统 (高危)';
@@ -1029,7 +1097,7 @@ class AppLocalizationsZh extends AppLocalizations {
String get taskDescHint => '简要说明此任务的用途';
@override
String get clearBeforeRun => '执行前清屏 (clear)';
String get clearBeforeRun => '执行前清屏';
@override
String get clearBeforeRunSubtitle => '在终端输出任务结果前清理历史屏幕';
@@ -1071,4 +1139,172 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get unsavedTaskChangesMessage => '当前任务内容已被修改,是否放弃未保存的修改并返回?';
@override
String get downloadSection => '下载';
@override
String get downloadSource => '下载源';
@override
String get selectDownloadSource => '选择下载源';
@override
String mirrorName(String mirror) {
String _temp0 = intl.Intl.selectLogic(mirror, {
'tsinghua': '清华大学开源软件镜像站 (推荐)',
'bfsu': '北京外国语大学开源软件镜像站',
'iscas': '中国科学院软件研究所开源镜像站',
'official': 'LinuxContainers 官方镜像源',
'other': '$mirror',
});
return '$_temp0';
}
@override
String get unnamedTask => '未命名任务';
@override
String get shellCommandHelperText => '支持单行指令(如 make)或多行 Shell 脚本(自动封装执行)';
@override
String get detectedTaskCmakeBuildRunDesc => '配置、编译并尝试启动生成的目标程序';
@override
String get detectedTaskCmakeBuildDesc => '仅执行 cmake 生成与构建';
@override
String get detectedTaskCmakeCleanDesc => '清理构建缓存目录';
@override
String get detectedTaskGradleRunDesc => '执行应用程序主入口';
@override
String get detectedTaskGradleAssembleDesc => '构建调试输出包';
@override
String get detectedTaskGradleBuildDesc => '执行完整构建与测试';
@override
String get detectedTaskMakeDefaultDesc => '执行默认 Makefile 构建目标';
@override
String get detectedTaskNpmStartDesc => '启动 Node 服务或前端开发环境';
@override
String get detectedTaskNpmTestDesc => '执行 npm test 测试套件';
@override
String get detectedTaskCargoRunDesc => '编译并运行 Rust 项目';
@override
String get detectedTaskCargoBuildDesc => '仅编译 Rust 项目';
@override
String get detectedTaskDartRunDesc => '启动 Dart 应用';
@override
String get detectedTaskSinglePythonDesc => '运行当前 Python 脚本';
@override
String get detectedTaskSingleCDesc => '编译并执行当前 C 源文件';
@override
String get detectedTaskSingleCppDesc => '编译并执行当前 C++ 源文件';
@override
String get detectedTaskSingleShDesc => '运行当前 Shell 脚本';
@override
String get detectedTaskSingleDartDesc => '运行当前 Dart 文件';
@override
String get detectedTaskSingleGoDesc => '运行当前 Go 源文件';
@override
String get detectedTaskSingleRustDesc => '编译并执行当前 Rust 源文件';
@override
String get detectedTaskSingleJsDesc => '运行当前 JS 脚本';
@override
String get missingDistroTitle => '系统环境未就绪';
@override
String get noDistroAvailableContent =>
'未检测到可用的 Linux 执行环境。\n\n工程任务需要在 Linux 容器环境中运行。请先安装或下载 Linux 系统(如 Ubuntu 或 Alpine)。';
@override
String distroNotInstalledContent(String distro) {
return '系统 \"$distro\" 尚未安装或已被清理。\n\n请在系统管理中安装该系统,或选择其他已就绪的系统。';
}
@override
String get openFromApp => '从软件内打开';
@override
String get openFromExternal => '从外部打开';
@override
String get projectsTitle => '项目';
@override
String get newProject => '新建项目';
@override
String get newProjectTitle => '新建项目';
@override
String get projectNameHint => '请输入项目名称';
@override
String get renameProject => '重命名项目';
@override
String get deleteProject => '删除项目';
@override
String deleteProjectConfirmMessage(String name) {
return '确定要删除项目 \"$name\" 吗?此操作不可逆。';
}
@override
String get projectAlreadyExists => '已存在同名项目';
@override
String get noProjects => '暂无项目,点击右上角新建项目';
@override
String get projectCreated => '项目创建成功';
@override
String get projectRenamed => '项目重命名成功';
@override
String get projectDeleted => '项目已删除';
@override
String get importFromExternal => '从外部导入';
@override
String get confirmProjectNameTitle => '确认项目名称';
@override
String get importingProject => '正在导入项目...';
@override
String get projectImported => '项目导入成功';
@override
String importProjectFailed(String error) {
return '导入项目失败: $error';
}
@override
String get unsupportedProjectArchiveFormat =>
'不支持的文件格式,仅支持压缩包格式 (.zip, .tar.gz, .tar.xz, .tar 等)';
@override
String get unsupportedDistroArchiveFormat =>
'不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)';
}
+129 -3
View File
@@ -164,7 +164,7 @@
"terminalInputHint": "输入命令...",
"sendCommandTooltip": "发送命令",
"importNewSystem": "导入新系统",
"importBuiltinAlpine": "从软件中导入 (Alpine)",
"importFromApp": "从软件中导入",
"importExternalTarGz": "从外部导入 (.tar.gz)",
"selectSystemDefaultPrompt": "选择系统将设为默认系统,新建终端时从该系统中启动:",
"noSystemsPrompt": "暂无系统,请点击右上角 \"+\" 导入",
@@ -205,6 +205,27 @@
}
},
"permanentDelete": "彻底删除",
"distroManagementTitle": "系统管理",
"installedStatus": "已安装",
"notInstalledStatus": "未安装",
"downloadingStatus": "下载中",
"downloadAction": "下载",
"installAction": "安装",
"builtinTag": "内置",
"cancelDownloadAction": "取消下载",
"cancelDownloadConfirmTitle": "取消下载",
"cancelDownloadConfirmMessage": "确定要取消正在下载的系统资源吗?已下载的部分将被清除。",
"deletingSystemProgress": "正在删除系统并清理数据,请稍候...",
"cannotDeleteBuiltinSystem": "内置系统受到保护,无法删除",
"recommendedTag": "推荐",
"downloadFailed": "下载失败: {error}",
"@downloadFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"deleteSystemSuccess": "已彻底删除系统 \"{name}\" 及关联会话",
"@deleteSystemSuccess": {
"placeholders": {
@@ -213,6 +234,33 @@
}
}
},
"deletePackageConfirmTitle": "确认删除安装包",
"deletePackageConfirmMessage": "确定要删除 \"{name}\" 的系统安装包吗?删除后可随时重新下载。",
"@deletePackageConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deletingPackageProgress": "正在删除安装包,请稍候...",
"deletePackageSuccess": "已删除 \"{name}\" 安装包",
"@deletePackageSuccess": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deletePackageTooltip": "删除已下载的系统安装包",
"importSystemInstanceTitle": "创建 {name} 系统实例",
"@importSystemInstanceTitle": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"deleteSystemTooltip": "彻底删除该系统 (高危)",
"preparingInitialization": "准备初始化...",
"cancellingAndCleaning": "正在取消并清理残余目录...",
@@ -481,7 +529,7 @@
"shellCommandEmptyError": "请输入执行指令",
"taskDescOptional": "任务描述(选填)",
"taskDescHint": "简要说明此任务的用途",
"clearBeforeRun": "执行前清屏 (clear)",
"clearBeforeRun": "执行前清屏",
"clearBeforeRunSubtitle": "在终端输出任务结果前清理历史屏幕",
"runTasksUpdated": "运行任务配置已更新",
"detectCompletedMessage": "探测完成,发现 {count} 个可用任务",
@@ -520,5 +568,83 @@
}
},
"unsavedTaskChangesTitle": "未保存的任务更改",
"unsavedTaskChangesMessage": "当前任务内容已被修改,是否放弃未保存的修改并返回?"
"unsavedTaskChangesMessage": "当前任务内容已被修改,是否放弃未保存的修改并返回?",
"downloadSection": "下载",
"downloadSource": "下载源",
"selectDownloadSource": "选择下载源",
"mirrorName": "{mirror, select, tsinghua{清华大学开源软件镜像站 (推荐)} bfsu{北京外国语大学开源软件镜像站} iscas{中国科学院软件研究所开源镜像站} official{LinuxContainers 官方镜像源} other{{mirror}}}",
"@mirrorName": {
"placeholders": {
"mirror": {
"type": "String"
}
}
},
"unnamedTask": "未命名任务",
"shellCommandHelperText": "支持单行指令(如 make)或多行 Shell 脚本(自动封装执行)",
"detectedTaskCmakeBuildRunDesc": "配置、编译并尝试启动生成的目标程序",
"detectedTaskCmakeBuildDesc": "仅执行 cmake 生成与构建",
"detectedTaskCmakeCleanDesc": "清理构建缓存目录",
"detectedTaskGradleRunDesc": "执行应用程序主入口",
"detectedTaskGradleAssembleDesc": "构建调试输出包",
"detectedTaskGradleBuildDesc": "执行完整构建与测试",
"detectedTaskMakeDefaultDesc": "执行默认 Makefile 构建目标",
"detectedTaskNpmStartDesc": "启动 Node 服务或前端开发环境",
"detectedTaskNpmTestDesc": "执行 npm test 测试套件",
"detectedTaskCargoRunDesc": "编译并运行 Rust 项目",
"detectedTaskCargoBuildDesc": "仅编译 Rust 项目",
"detectedTaskDartRunDesc": "启动 Dart 应用",
"detectedTaskSinglePythonDesc": "运行当前 Python 脚本",
"detectedTaskSingleCDesc": "编译并执行当前 C 源文件",
"detectedTaskSingleCppDesc": "编译并执行当前 C++ 源文件",
"detectedTaskSingleShDesc": "运行当前 Shell 脚本",
"detectedTaskSingleDartDesc": "运行当前 Dart 文件",
"detectedTaskSingleGoDesc": "运行当前 Go 源文件",
"detectedTaskSingleRustDesc": "编译并执行当前 Rust 源文件",
"detectedTaskSingleJsDesc": "运行当前 JS 脚本",
"missingDistroTitle": "系统环境未就绪",
"noDistroAvailableContent": "未检测到可用的 Linux 执行环境。\n\n工程任务需要在 Linux 容器环境中运行。请先安装或下载 Linux 系统(如 Ubuntu 或 Alpine)。",
"distroNotInstalledContent": "系统 \"{distro}\" 尚未安装或已被清理。\n\n请在系统管理中安装该系统,或选择其他已就绪的系统。",
"@distroNotInstalledContent": {
"placeholders": {
"distro": {
"type": "String"
}
}
},
"openFromApp": "从软件内打开",
"openFromExternal": "从外部打开",
"projectsTitle": "项目",
"newProject": "新建项目",
"newProjectTitle": "新建项目",
"projectNameHint": "请输入项目名称",
"renameProject": "重命名项目",
"deleteProject": "删除项目",
"deleteProjectConfirmMessage": "确定要删除项目 \"{name}\" 吗?此操作不可逆。",
"@deleteProjectConfirmMessage": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"projectAlreadyExists": "已存在同名项目",
"noProjects": "暂无项目,点击右上角新建项目",
"projectCreated": "项目创建成功",
"projectRenamed": "项目重命名成功",
"projectDeleted": "项目已删除",
"importFromExternal": "从外部导入",
"confirmProjectNameTitle": "确认项目名称",
"importingProject": "正在导入项目...",
"projectImported": "项目导入成功",
"importProjectFailed": "导入项目失败: {error}",
"@importProjectFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"unsupportedProjectArchiveFormat": "不支持的文件格式,仅支持压缩包格式 (.zip, .tar.gz, .tar.xz, .tar 等)",
"unsupportedDistroArchiveFormat": "不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)"
}
+273
View File
@@ -0,0 +1,273 @@
import 'dart:ffi';
import 'package:flutter/material.dart';
/// 系统架构类型
enum DistroArch {
arm64,
x86_64,
}
/// LXC 容器镜像元数据规格(用于根据下载源动态解析真实下载路径)
class LxcImageSpec {
/// 发行版代号 (例如 'debian', 'archlinux', 'fedora')
final String distribution;
/// 版本标识 (例如 'bookworm', 'current', '43')
final String release;
/// 变体标识 (例如 'default', 'cloud')
final String variant;
const LxcImageSpec({
required this.distribution,
required this.release,
this.variant = 'default',
});
}
/// 发行版下载镜像源定义
class DistroMirror {
final String id;
final String name;
final String baseUrl;
final bool isDefault;
const DistroMirror({
required this.id,
required this.name,
required this.baseUrl,
this.isDefault = false,
});
}
/// 发行版条目清单模型
class DistroManifestItem {
/// 唯一标识符 (例如 'ubuntu', 'alpine', 'debian')
final String id;
/// 显示名称 (例如 'Ubuntu', 'Alpine Linux', 'Debian')
final String name;
/// 版本文本 (例如 '24.04.5 LTS', '3.20.3', '12 (Bookworm)')
final String version;
/// 是否推荐
final bool isRecommended;
/// 是否为软件内置安装包(打包在 assets 中,受删除保护且无需网络下载)
final bool isBuiltin;
/// LXC 镜像元数据(在线下载型系统专属,用于动态源解析器自动发现真实路径)
final LxcImageSpec? lxcSpec;
/// 对应架构资源包映射 (架构 -> 下载 URL 或 Asset 路径)
final Map<DistroArch, String> packages;
/// 系统图标或装饰图标
final IconData iconData;
/// 品牌主题色(用于图标底色/装饰)
final Color brandColor;
/// 本地资产图标路径 (例如 'assets/icons/distros/ubuntu.png')
final String? assetIconPath;
const DistroManifestItem({
required this.id,
required this.name,
required this.version,
this.isRecommended = false,
this.isBuiltin = false,
this.lxcSpec,
required this.packages,
required this.iconData,
required this.brandColor,
this.assetIconPath,
});
/// 获取当前运行环境的 CPU 架构
static DistroArch get currentArch {
final abi = Abi.current();
if (abi == Abi.androidArm64 || abi == Abi.linuxArm64) {
return DistroArch.arm64;
}
return DistroArch.x86_64;
}
/// 当前机器架构是否有可用的资源包
bool get isSupportedOnCurrentDevice {
return packages.containsKey(currentArch);
}
/// 获取当前设备适用的资源包路径或 URL
String? get currentPackageSource {
return packages[currentArch];
}
}
/// 系统资源库静态目录(包含内置与经过验证的高速在线源)
class DistroRepository {
static const List<DistroManifestItem> availableDistros = [
// 1. Ubuntu 24.04 LTS (推荐,软件内置)
DistroManifestItem(
id: 'ubuntu',
name: 'Ubuntu',
version: '24.04.5 LTS (Noble Numbat)',
isRecommended: true,
isBuiltin: true,
iconData: Icons.donut_large_rounded,
brandColor: Color(0xFFE95420), // Ubuntu Orange
assetIconPath: 'assets/icons/distros/ubuntu.png',
packages: {
DistroArch.arm64: 'assets/distros/ubuntu-base-24.04.5-base-arm64.tar.gz',
DistroArch.x86_64: 'assets/distros/ubuntu-base-24.04.5-base-x86_64.tar.gz',
},
),
// 2. Alpine 3.20 (软件内置)
DistroManifestItem(
id: 'alpine',
name: 'Alpine Linux',
version: '3.20.3 (musl libc)',
isRecommended: false,
isBuiltin: true,
iconData: Icons.landscape_rounded,
brandColor: Color(0xFF0D597F), // Alpine Blue
assetIconPath: 'assets/icons/distros/alpine.png',
packages: {
DistroArch.arm64: 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz',
DistroArch.x86_64: 'assets/distros/alpine-minirootfs-3.20.3-x86_64.tar.gz',
},
),
// 3. Debian 12 (Bookworm) - 在线下载,不占 APK 体积
DistroManifestItem(
id: 'debian',
name: 'Debian',
version: '12 (Bookworm)',
isRecommended: false,
isBuiltin: false,
lxcSpec: LxcImageSpec(
distribution: 'debian',
release: 'bookworm',
variant: 'default',
),
iconData: Icons.all_inclusive_rounded,
brandColor: Color(0xFFA80030), // Debian Red
assetIconPath: 'assets/icons/distros/debian.png',
packages: {
DistroArch.arm64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/arm64/default/20260913_05:24/rootfs.tar.xz',
DistroArch.x86_64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/amd64/default/20260913_05:24/rootfs.tar.xz',
},
),
// 4. Arch Linux - 在线源
DistroManifestItem(
id: 'arch',
name: 'Arch Linux',
version: 'Rolling Release',
isRecommended: false,
isBuiltin: false,
lxcSpec: LxcImageSpec(
distribution: 'archlinux',
release: 'current',
variant: 'default',
),
iconData: Icons.change_history_rounded,
brandColor: Color(0xFF1793D1), // Arch Cyan
assetIconPath: 'assets/icons/distros/arch.png',
packages: {
DistroArch.arm64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/archlinux/current/arm64/default/20260913_04:18/rootfs.tar.xz',
DistroArch.x86_64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/archlinux/current/amd64/default/20260913_04:18/rootfs.tar.xz',
},
),
// 5. Fedora 43 - 在线源
DistroManifestItem(
id: 'fedora',
name: 'Fedora',
version: '43 (Container Base)',
isRecommended: false,
isBuiltin: false,
lxcSpec: LxcImageSpec(
distribution: 'fedora',
release: '43',
variant: 'default',
),
iconData: Icons.language_rounded,
brandColor: Color(0xFF51A2DA), // Fedora Blue
assetIconPath: 'assets/icons/distros/fedora.png',
packages: {
DistroArch.arm64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/fedora/43/arm64/default/20260913_20:33/rootfs.tar.xz',
DistroArch.x86_64: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/fedora/43/amd64/default/20260913_20:33/rootfs.tar.xz',
},
),
];
/// 可选的高速开源软件镜像源
static const List<DistroMirror> availableMirrors = [
DistroMirror(
id: 'tsinghua',
name: 'Tsinghua TUNA Mirror',
baseUrl: 'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/',
isDefault: true,
),
DistroMirror(
id: 'bfsu',
name: 'BFSU Open Source Mirror',
baseUrl: 'https://mirrors.bfsu.edu.cn/lxc-images/',
),
DistroMirror(
id: 'iscas',
name: 'ISCAS Open Source Mirror',
baseUrl: 'https://mirror.iscas.ac.cn/lxc-images/',
),
DistroMirror(
id: 'official',
name: 'LinuxContainers Official Mirror',
baseUrl: 'https://images.linuxcontainers.org/',
),
];
/// 默认推荐镜像源(清华大学源)
static DistroMirror get defaultMirror =>
availableMirrors.firstWhere((m) => m.isDefault, orElse: () => availableMirrors.first);
/// 根据 ID 检索镜像源
static DistroMirror getMirrorById(String id) {
return availableMirrors.firstWhere(
(m) => m.id == id,
orElse: () => defaultMirror,
);
}
/// 根据当前机器架构过滤,仅返回本架构支持的发行版列表
static List<DistroManifestItem> get currentArchDistros {
return availableDistros.where((d) => d.isSupportedOnCurrentDevice).toList();
}
/// 默认系统实例名称
static const String defaultSystemName = 'ubuntu';
/// 根据 ID 查找发行版配置
static DistroManifestItem? getById(String id) {
try {
return availableDistros.firstWhere((e) => e.id == id);
} catch (_) {
return null;
}
}
/// 内置 Ubuntu 资源包路径(自动匹配当前 CPU 架构)
static String get builtinUbuntuAssetPath {
return getById('ubuntu')?.currentPackageSource ??
'assets/distros/ubuntu-base-24.04.5-base-arm64.tar.gz';
}
/// 内置 Alpine 资源包路径(自动匹配当前 CPU 架构)
static String get builtinAlpineAssetPath {
return getById('alpine')?.currentPackageSource ??
'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz';
}
}
+68 -6
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
/// 运行任务来源类型
enum TaskSource {
@@ -48,14 +49,19 @@ class RunTask {
/// 从持久化的 JSON Map 构建自定义运行任务
factory RunTask.fromJson(Map<String, dynamic> json) {
final rawClear = json['clearBeforeRun'];
final bool clearVal = (rawClear is bool)
? rawClear
: (rawClear is num ? rawClear != 0 : (rawClear?.toString().toLowerCase() == 'true'));
return RunTask(
id: json['id'] as String? ?? 'custom_${DateTime.now().microsecondsSinceEpoch}',
name: json['name'] as String? ?? '未命名任务',
command: json['command'] as String? ?? '',
id: json['id']?.toString() ?? 'custom_${DateTime.now().microsecondsSinceEpoch}',
name: json['name']?.toString() ?? '未命名任务',
command: json['command']?.toString() ?? '',
source: TaskSource.custom,
description: json['description'] as String?,
workingDir: json['workingDir'] as String?,
clearBeforeRun: json['clearBeforeRun'] as bool? ?? false,
description: json['description']?.toString(),
workingDir: json['workingDir']?.toString(),
clearBeforeRun: clearVal,
);
}
@@ -71,6 +77,62 @@ class RunTask {
};
}
/// 获取多语言本地化的任务描述/小字(自动根据系统探测任务 ID 映射,未匹配或自定义任务返回原本的 description)
String getLocalizedDescription(AppLocalizations l10n) {
switch (id) {
case 'detected_cmake_build_run':
return l10n.detectedTaskCmakeBuildRunDesc;
case 'detected_cmake_build':
return l10n.detectedTaskCmakeBuildDesc;
case 'detected_cmake_clean':
return l10n.detectedTaskCmakeCleanDesc;
case 'detected_gradle_run':
return l10n.detectedTaskGradleRunDesc;
case 'detected_gradle_assemble':
return l10n.detectedTaskGradleAssembleDesc;
case 'detected_gradle_build':
return l10n.detectedTaskGradleBuildDesc;
case 'detected_make_default':
return l10n.detectedTaskMakeDefaultDesc;
case 'detected_npm_start':
return l10n.detectedTaskNpmStartDesc;
case 'detected_npm_test':
return l10n.detectedTaskNpmTestDesc;
case 'detected_cargo_run':
return l10n.detectedTaskCargoRunDesc;
case 'detected_cargo_build':
return l10n.detectedTaskCargoBuildDesc;
case 'detected_dart_run':
return l10n.detectedTaskDartRunDesc;
case 'detected_single_python':
return l10n.detectedTaskSinglePythonDesc;
case 'detected_single_c':
return l10n.detectedTaskSingleCDesc;
case 'detected_single_cpp':
return l10n.detectedTaskSingleCppDesc;
case 'detected_single_sh':
return l10n.detectedTaskSingleShDesc;
case 'detected_single_dart':
return l10n.detectedTaskSingleDartDesc;
case 'detected_single_go':
return l10n.detectedTaskSingleGoDesc;
case 'detected_single_rust':
return l10n.detectedTaskSingleRustDesc;
case 'detected_single_js':
return l10n.detectedTaskSingleJsDesc;
default:
return description ?? '';
}
}
/// 获取多语言本地化的任务名称(自定义且为默认名时返回对应语言的“未命名任务”)
String getLocalizedName(AppLocalizations l10n) {
if (name == '未命名任务' || name == 'Unnamed Task') {
return l10n.unnamedTask;
}
return name;
}
RunTask copyWith({
String? id,
String? name,
+49
View File
@@ -18,6 +18,7 @@ class TerminalSession {
Pty? _pty;
StreamSubscription? _ptyOutputSub;
bool _isProcessRunning = false;
Completer<bool>? _processCompleter;
VoidCallback? onProcessTerminated;
TerminalSession({
@@ -40,6 +41,9 @@ class TerminalSession {
bool get isProcessRunning => _isProcessRunning;
/// 获取终端进程启动就绪的 Future
Future<bool>? get onProcessReady => _processCompleter?.future;
/// 获取终端缓冲区当前全部可见文本(常用于测试与日志断言)
String get bufferText => terminal.buffer.getText();
@@ -65,6 +69,9 @@ class TerminalSession {
/// 启动底层真实 PTY 进程(连接 PRoot 容器或 Host Shell)
Future<void> startProcess({DistroManager? distroManager, String? workspacePath}) async {
if (_processCompleter == null || _processCompleter!.isCompleted) {
_processCompleter = Completer<bool>();
}
final manager = distroManager ?? DistroManager();
final effectiveWorkspace = workspacePath ?? this.workspacePath;
try {
@@ -86,6 +93,9 @@ class TerminalSession {
columns: initialCols,
);
_isProcessRunning = true;
if (!(_processCompleter?.isCompleted ?? true)) {
_processCompleter?.complete(true);
}
// PTY 输出数据流实时解码并写入终端
_ptyOutputSub = _pty!.output.listen(
@@ -108,11 +118,50 @@ class TerminalSession {
});
} catch (e) {
_isProcessRunning = false;
if (!(_processCompleter?.isCompleted ?? true)) {
_processCompleter?.complete(false);
}
terminal.write('\x1b[31m[PTY launch failed: $e]\x1b[0m\r\n');
onProcessTerminated?.call();
}
}
/// 等待终端底层伪终端进程启动并就绪
Future<bool> waitForReady({Duration timeout = const Duration(seconds: 10)}) async {
if (_isProcessRunning && _pty != null) return true;
if (_processCompleter != null) {
try {
return await _processCompleter!.future.timeout(timeout, onTimeout: () => false);
} catch (_) {
return false;
}
}
return false;
}
/// 向终端底层伪终端 (PTY) 真正写入待执行指令
///
/// 该方法通过 [_pty.write] 向进程标准输入通道写入指令并换行,触发 Shell 真正执行任务,
/// 所有输出实时经由 PTY 流向终端画布呈现给用户。
Future<void> executeCommand(String command) async {
if (!_isProcessRunning && _processCompleter == null) {
unawaited(startProcess());
}
final isReady = await waitForReady();
if (isReady && _pty != null && _isProcessRunning) {
// 适度微延迟确保 Shell 终端行纪律(termios)已就绪并开始监听 stdin
await Future<void>.delayed(const Duration(milliseconds: 60));
try {
_pty!.write(utf8.encode('$command\n'));
} catch (e) {
terminal.write('\r\n\x1b[31m[写入终端失败: $e]\x1b[0m\r\n');
}
} else {
terminal.write('\r\n\x1b[31m[无法执行命令:终端环境未启动或启动失败]\x1b[0m\r\n');
}
}
/// 向终端写入文本(支持 VT100 / ANSI 转义序列)
void write(String text) {
terminal.write(text);
+18 -1
View File
@@ -70,7 +70,24 @@ class DistroProvider with ChangeNotifier {
}
}
/// 从应用内置资源导入 Alpine 系统实例
/// 从应用内置资源导入 Ubuntu 24.04 系统实例
Future<void> importBuiltinUbuntu({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await _manager.importBuiltinUbuntu(
systemName: systemName,
onProgress: onProgress,
isCancelled: isCancelled,
);
// 导入成功后刷新列表并自动选为当前系统
await refreshSystems();
await selectSystem(systemName);
}
/// 从应用内置资源导入 Alpine 系统实例(保留备用)
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
+25
View File
@@ -152,6 +152,31 @@ class ProjectProvider extends ChangeNotifier {
}
}
// 打开指定路径的项目
Future<void> openSpecificDirectory(String directoryPath) async {
try {
if (directoryPath.trim().isEmpty) return;
final cleanPath = p.normalize(directoryPath.trim());
final currentRoot = _history.rootPath != null ? p.normalize(_history.rootPath!) : null;
final isSameRoot = currentRoot != null && cleanPath == currentRoot;
await ProjectHistoryService.instance.recordHistory(
rootPath: cleanPath,
lastOpenedFilePath: isSameRoot ? _history.lastOpenedFilePath : null,
openDirectoryPaths: isSameRoot ? _history.openDirectoryPaths : const [],
openFilePaths: isSameRoot ? _history.openFilePaths : const [],
);
_cutItem = null;
_copiedItem = null;
await _loadProjectFromHistory();
} catch (e) {
debugPrint('打开指定项目失败: $e');
}
}
//选择项目历史
Future<void> switchProject(ProjectHistory selectedHistory) async {
final selectedRoot = selectedHistory.rootPath;
+13
View File
@@ -40,6 +40,7 @@ class RunProvider extends ChangeNotifier {
/// 内部方法:尝试从现有任务列表中匹配 lastRunTaskId
void _resolveLastRunTask() {
_lastRunTask = null;
if (_lastRunTaskId == null) return;
for (final task in allTasks) {
if (task.id == _lastRunTaskId) {
@@ -67,8 +68,17 @@ class RunProvider extends ChangeNotifier {
/// 当打开或切换工程时初始化任务(读取持久化任务 + 首次自动探测系统任务)
Future<void> onProjectOpened(String projectRoot, {String? activeFilePath}) async {
_currentProjectRoot = projectRoot;
// 切换工程时首先立即清空上一工程的内存任务状态,防止跨项目污染
_detectedTasks = [];
_customTasks = [];
_lastRunTaskId = null;
_lastRunTask = null;
notifyListeners();
// 1. 加载持久化的自定义任务与最近运行任务ID
final config = await _storageService.loadConfig(projectRoot);
if (_currentProjectRoot != projectRoot) return;
_customTasks = config.tasks;
_lastRunTaskId = config.lastRunTaskId;
_resolveLastRunTask();
@@ -101,6 +111,7 @@ class RunProvider extends ChangeNotifier {
_isDetecting = true;
// 清空内存中的旧探测结果
_detectedTasks = [];
_resolveLastRunTask();
notifyListeners();
try {
@@ -108,8 +119,10 @@ class RunProvider extends ChangeNotifier {
projectRoot: projectRoot,
currentFilePath: currentFilePath,
);
if (_currentProjectRoot == projectRoot) {
_detectedTasks = detected;
_resolveLastRunTask();
}
} catch (e) {
debugPrint('[RunProvider] 项目探测失败: $e');
} finally {
+24
View File
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/models/editor_theme.dart';
import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:flutter/foundation.dart';
@@ -30,6 +31,9 @@ class SettingsProvider extends ChangeNotifier {
//项目配置
static const String _keyShowHiddenFiles = 'show_hidden_files'; //显示隐藏文件
//下载配置
static const String _keyDownloadMirrorId = 'download_mirror_id'; //下载源镜像ID
//语言
static const String _keyAppLocale = 'app_locale';
@@ -50,9 +54,12 @@ class SettingsProvider extends ChangeNotifier {
String _terminalKeyboardConfigJson = VirtualKeyboardConfig.defaultTerminalJsonPretty();
VirtualKeyboardConfig _terminalKeyboardConfig = VirtualKeyboardConfig.defaultTerminalConfiguration();
bool _showHiddenFiles = true;
String _downloadMirrorId = 'tsinghua'; // 默认清华源
Locale? _locale;
bool get showHiddenFiles => _showHiddenFiles;
String get downloadMirrorId => _downloadMirrorId;
DistroMirror get downloadMirror => DistroRepository.getMirrorById(_downloadMirrorId);
ThemeMode get appThemeMode => _appThemeMode;
Color get appThemeColor => _appThemeColor;
@@ -260,6 +267,12 @@ class SettingsProvider extends ChangeNotifier {
_showHiddenFiles = savedShowHiddenFiles;
}
//设置下载源镜像配置
final savedMirrorId = prefs.getString(_keyDownloadMirrorId);
if (savedMirrorId != null && savedMirrorId.isNotEmpty) {
_downloadMirrorId = savedMirrorId;
}
//设置语言
final savedLocale = prefs.getString(_keyAppLocale);
if(savedLocale != null && savedLocale.isNotEmpty) {
@@ -412,4 +425,15 @@ class SettingsProvider extends ChangeNotifier {
await prefs.setBool(_keyShowHiddenFiles, show);
} catch (_) {}
}
/// 设置系统安装包下载镜像源
Future<void> setDownloadMirrorId(String mirrorId) async {
if (_downloadMirrorId == mirrorId) return;
_downloadMirrorId = mirrorId;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyDownloadMirrorId, mirrorId);
} catch (_) {}
}
}
+1
View File
@@ -26,6 +26,7 @@ class TabProvider extends ChangeNotifier {
String? get currentFilePath => _activeFilePath;
bool get isModified => activeTab?.isModified ?? _isModified;
bool get hasUnsavedChanges => _isModified || _openTabs.any((t) => t.isModified);
void bindProjectProvider(ProjectProvider projectProvider) {
if (_projectProvider == projectProvider) return;
+18 -5
View File
@@ -1,3 +1,4 @@
import 'dart:async';
import 'package:code_editor/models/terminal_session.dart';
import 'package:flutter/material.dart';
@@ -26,9 +27,15 @@ class TerminalProvider extends ChangeNotifier {
void ensureInitialized({
String defaultName = '会话',
String defaultDistroId = 'alpine',
String? workspacePath,
}) {
if (_sessions.isEmpty) {
createSession(name: defaultName, distroId: defaultDistroId, activate: true);
createSession(
name: defaultName,
distroId: defaultDistroId,
workspacePath: workspacePath,
activate: true,
);
}
}
@@ -66,17 +73,23 @@ class TerminalProvider extends ChangeNotifier {
return session;
}
/// 查找或复用绑定了指定工程路径的终端会话
/// 查找或复用绑定了指定工程路径与系统实例的终端会话
/// 如果存在,直接激活并返回;如果不存在,则新建并激活一个会话
TerminalSession getOrCreateSessionForProject({
required String projectRoot,
String distroId = 'alpine',
String distroId = 'ubuntu',
String? sessionName,
}) {
final index = _sessions.indexWhere((s) => s.workspacePath == projectRoot);
final index = _sessions.indexWhere(
(s) => s.workspacePath == projectRoot && s.distroId == distroId,
);
if (index != -1) {
final session = _sessions[index];
selectSession(index);
return _sessions[index];
if (!session.isProcessRunning) {
unawaited(session.startProcess());
}
return session;
}
return createSession(
+448
View File
@@ -0,0 +1,448 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../models/distro_manifest.dart';
import 'distro_image_resolver.dart';
/// 系统包下载状态枚举
enum DistroDownloadState {
notStarted,
downloading,
completed,
cancelled,
failed,
}
/// 单个系统的下载状态快照
class DistroDownloadProgress {
final String distroId;
final DistroDownloadState state;
final double progress; // 0.0 ~ 1.0
final int receivedBytes;
final int totalBytes;
final String? errorMessage;
final File? targetFile;
const DistroDownloadProgress({
required this.distroId,
required this.state,
this.progress = 0.0,
this.receivedBytes = 0,
this.totalBytes = -1,
this.errorMessage,
this.targetFile,
});
DistroDownloadProgress copyWith({
DistroDownloadState? state,
double? progress,
int? receivedBytes,
int? totalBytes,
String? errorMessage,
File? targetFile,
}) {
return DistroDownloadProgress(
distroId: distroId,
state: state ?? this.state,
progress: progress ?? this.progress,
receivedBytes: receivedBytes ?? this.receivedBytes,
totalBytes: totalBytes ?? this.totalBytes,
errorMessage: errorMessage ?? this.errorMessage,
targetFile: targetFile ?? this.targetFile,
);
}
}
/// 下载被取消异常
class DistroDownloadCancelledException implements Exception {
final String message;
const DistroDownloadCancelledException([this.message = 'Download cancelled']);
@override
String toString() => message;
}
/// 全局异步系统镜像下载管理器(单例模式)
class DistroDownloadManager extends ChangeNotifier {
static final DistroDownloadManager _instance = DistroDownloadManager._internal();
factory DistroDownloadManager() => _instance;
DistroDownloadManager._internal();
final Map<String, DistroDownloadProgress> _progressMap = {};
final Map<String, HttpClientRequest> _activeRequests = {};
final Map<String, HttpClient> _activeClients = {};
final Map<String, StreamSubscription<List<int>>> _activeSubscriptions = {};
final Map<String, IOSink> _activeSinks = {};
final Map<String, Completer<void>> _activeCompleters = {};
final Set<String> _cancelledDistroIds = {};
@visibleForTesting
Directory? customPackagesDir;
/// 获取系统安装包持久化存储目录: `<app_dir>/distro_packages`
Future<Directory> getPackagesDir() async {
if (customPackagesDir != null) return customPackagesDir!;
final appDir = await getApplicationSupportDirectory();
final dir = Directory(p.join(appDir.path, 'distro_packages'));
if (!dir.existsSync()) {
dir.createSync(recursive: true);
}
return dir;
}
/// 获取指定系统的安装包文件对象
Future<File> getPackageFile(String distroId, [String? downloadUrl]) async {
final dir = await getPackagesDir();
final ext = (downloadUrl?.endsWith('.tar.gz') ?? false) ? '.tar.gz' : '.tar.xz';
final targetFile = File(p.join(dir.path, '${distroId}_rootfs$ext'));
if (targetFile.existsSync()) return targetFile;
final altExt = ext == '.tar.xz' ? '.tar.gz' : '.tar.xz';
final altFile = File(p.join(dir.path, '${distroId}_rootfs$altExt'));
if (altFile.existsSync()) return altFile;
return targetFile;
}
/// 检测指定系统的离线安装包是否已下载完备
Future<bool> isPackageDownloaded(String distroId, [String? downloadUrl]) async {
final dir = await getPackagesDir();
final xzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.xz'));
final gzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.gz'));
return (xzFile.existsSync() && xzFile.lengthSync() > 0) ||
(gzFile.existsSync() && gzFile.lengthSync() > 0);
}
/// 物理删除已下载的系统安装包
Future<void> deletePackage(String distroId, [String? downloadUrl]) async {
if (isDownloading(distroId)) {
await cancelDownload(distroId);
}
final dir = await getPackagesDir();
final files = [
File(p.join(dir.path, '${distroId}_rootfs.tar.xz')),
File(p.join(dir.path, '${distroId}_rootfs.tar.gz')),
];
for (final f in files) {
if (f.existsSync()) {
try {
f.deleteSync();
} catch (_) {}
}
}
_progressMap.remove(distroId);
notifyListeners();
}
/// 获取所有正在跟踪的下载任务快照
Map<String, DistroDownloadProgress> get allProgress => Map.unmodifiable(_progressMap);
/// 查询指定系统的下载状态
DistroDownloadProgress? getProgress(String distroId) => _progressMap[distroId];
/// 是否正在下载
bool isDownloading(String distroId) {
final status = _progressMap[distroId];
return status != null && status.state == DistroDownloadState.downloading;
}
/// 启动异步流式下载
Future<File?> startDownload({
required String distroId,
required String downloadUrl,
DistroMirror? mirror,
DistroManifestItem? manifestItem,
}) async {
if (isDownloading(distroId)) return null;
// 资源检测:若本地已存在完整的离线镜像包,拒绝重复下载并直接返回已有文件
if (await isPackageDownloaded(distroId, downloadUrl)) {
final existingFile = await getPackageFile(distroId, downloadUrl);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
targetFile: existingFile,
);
notifyListeners();
return existingFile;
}
// 清除历史取消标记
_cancelledDistroIds.remove(distroId);
// 状态更新为 downloading
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.downloading,
progress: 0.0,
);
notifyListeners();
String actualDownloadUrl = downloadUrl;
if (manifestItem != null && manifestItem.lxcSpec != null) {
try {
final activeMirror = mirror ?? DistroRepository.defaultMirror;
actualDownloadUrl = await DistroImageResolver().resolveDownloadUrl(
item: manifestItem,
arch: DistroManifestItem.currentArch,
mirror: activeMirror,
);
} catch (e) {
if (_cancelledDistroIds.contains(distroId)) {
_cleanupCancelledState(distroId);
return null;
}
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.failed,
errorMessage: e.toString(),
);
notifyListeners();
return null;
}
}
if (_cancelledDistroIds.contains(distroId)) {
_cleanupCancelledState(distroId);
return null;
}
// 二次资源检测:解析目标 URL 后再次检测文件是否完备
if (await isPackageDownloaded(distroId, actualDownloadUrl)) {
final existingFile = await getPackageFile(distroId, actualDownloadUrl);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
targetFile: existingFile,
);
notifyListeners();
return existingFile;
}
final targetFile = await getPackageFile(distroId, actualDownloadUrl);
final partFilePath = '${targetFile.path}.part';
final partFile = File(partFilePath);
HttpClient? client;
IOSink? sink;
StreamSubscription<List<int>>? subscription;
final completer = Completer<void>();
_activeCompleters[distroId] = completer;
try {
if (partFile.existsSync()) {
try {
partFile.deleteSync();
} catch (_) {}
}
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
client = HttpClient()
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
_activeClients[distroId] = client;
final uri = Uri.parse(actualDownloadUrl);
final request = await client.getUrl(uri);
_activeRequests[distroId] = request;
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
final response = await request.close();
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
if (response.statusCode != HttpStatus.ok) {
throw HttpException('HTTP Error: ${response.statusCode} ${response.reasonPhrase}');
}
final total = response.contentLength;
int received = 0;
sink = partFile.openWrite();
_activeSinks[distroId] = sink;
subscription = response.listen(
(chunk) {
if (_cancelledDistroIds.contains(distroId)) {
subscription?.cancel();
return;
}
sink?.add(chunk);
received += chunk.length;
final prog = total > 0 ? (received / total).clamp(0.0, 1.0) : 0.0;
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.downloading,
progress: prog,
receivedBytes: received,
totalBytes: total,
);
notifyListeners();
},
onDone: () async {
if (_cancelledDistroIds.contains(distroId)) {
if (!completer.isCompleted) {
completer.completeError(const DistroDownloadCancelledException());
}
return;
}
try {
await sink?.flush();
await sink?.close();
sink = null;
} catch (_) {}
if (!completer.isCompleted) {
completer.complete();
}
},
onError: (e) {
if (!completer.isCompleted) {
completer.completeError(e);
}
},
cancelOnError: true,
);
_activeSubscriptions[distroId] = subscription;
await completer.future;
if (_cancelledDistroIds.contains(distroId)) {
throw const DistroDownloadCancelledException();
}
// 下载完成,原子重命名 .part -> targetFile
if (targetFile.existsSync()) {
targetFile.deleteSync();
}
partFile.renameSync(targetFile.path);
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.completed,
progress: 1.0,
receivedBytes: received,
totalBytes: total,
targetFile: targetFile,
);
notifyListeners();
return targetFile;
} catch (e) {
final isCancelled = _cancelledDistroIds.contains(distroId) ||
e is DistroDownloadCancelledException;
// 无论如何先关闭写入流,确保文件句柄释放
try {
await sink?.close();
} catch (_) {}
// 清理临时文件
if (partFile.existsSync()) {
try {
partFile.deleteSync();
} catch (_) {}
}
if (isCancelled) {
_cleanupCancelledState(distroId);
} else {
_progressMap[distroId] = DistroDownloadProgress(
distroId: distroId,
state: DistroDownloadState.failed,
errorMessage: e.toString(),
);
notifyListeners();
}
return null;
} finally {
_activeRequests.remove(distroId);
_activeSubscriptions.remove(distroId);
_activeSinks.remove(distroId);
_activeCompleters.remove(distroId);
final c = _activeClients.remove(distroId);
try {
c?.close(force: true);
} catch (_) {}
_cancelledDistroIds.remove(distroId);
}
}
/// 取消下载并清理已下载的临时缓存资源
Future<void> cancelDownload(String distroId) async {
_cancelledDistroIds.add(distroId);
// 1. 中断活跃 Completer
final completer = _activeCompleters.remove(distroId);
if (completer != null && !completer.isCompleted) {
completer.completeError(const DistroDownloadCancelledException());
}
// 2. 中断 Request 并强力关闭 HttpClient(立即熔断底层 TCP Socket,避免 sub.cancel() 陷入 socket 耗尽等待)
final request = _activeRequests.remove(distroId);
if (request != null) {
try {
request.abort();
} catch (_) {}
}
final client = _activeClients.remove(distroId);
if (client != null) {
try {
client.close(force: true);
} catch (_) {}
}
// 3. 取消活跃 Stream 订阅以停止接收数据包(不阻塞等待 drain)
final sub = _activeSubscriptions.remove(distroId);
if (sub != null) {
try {
unawaited(sub.cancel());
} catch (_) {}
}
// 4. 关闭文件写入流以释放文件句柄(Windows 平台必须关闭方可删除)
final sink = _activeSinks.remove(distroId);
if (sink != null) {
try {
await sink.close();
} catch (_) {}
}
// 5. 立即清除临时 .part 文件
try {
final dir = await getPackagesDir();
final partFiles = [
File(p.join(dir.path, '${distroId}_rootfs.tar.gz.part')),
File(p.join(dir.path, '${distroId}_rootfs.tar.xz.part')),
];
for (final f in partFiles) {
if (f.existsSync()) {
f.deleteSync();
}
}
} catch (_) {}
// 6. 重置状态并通知刷新
_cleanupCancelledState(distroId);
}
void _cleanupCancelledState(String distroId) {
_progressMap.remove(distroId);
notifyListeners();
}
/// 重置已完成或失败的状态
void resetState(String distroId) {
_progressMap.remove(distroId);
notifyListeners();
}
}
+183
View File
@@ -0,0 +1,183 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import '../models/distro_manifest.dart';
/// LXC 镜像源索引行条目
class DistroIndexEntry {
final String distribution;
final String release;
final String arch;
final String variant;
final String buildDate;
final String path;
const DistroIndexEntry({
required this.distribution,
required this.release,
required this.arch,
required this.variant,
required this.buildDate,
required this.path,
});
factory DistroIndexEntry.fromLine(String line) {
final parts = line.trim().split(';');
if (parts.length < 6) {
throw FormatException('Invalid index line: $line');
}
return DistroIndexEntry(
distribution: parts[0],
release: parts[1],
arch: parts[2],
variant: parts[3],
buildDate: parts[4],
path: parts[5],
);
}
}
/// 发行版镜像真实下载链接解析器(遵循 LinuxContainers 标准 index-system 规范)
class DistroImageResolver {
static final DistroImageResolver _instance = DistroImageResolver._internal();
factory DistroImageResolver() => _instance;
DistroImageResolver._internal();
/// 缓存的解析结果 (key: "mirrorId:distroId:arch", value: url)
final Map<String, String> _resolvedUrlCache = {};
/// 缓存的 index-system 纯文本内容 (key: mirrorId, value: (cachedTime, content))
final Map<String, (DateTime, String)> _indexContentCache = {};
/// 索引缓存有效期 (1 小时)
static const Duration cacheTtl = Duration(hours: 1);
@visibleForTesting
String? customIndexContent;
/// 清空指定系统或所有缓存
void invalidateCache({String? distroId}) {
if (distroId != null) {
_resolvedUrlCache.removeWhere((key, _) => key.contains(':$distroId:'));
} else {
_resolvedUrlCache.clear();
_indexContentCache.clear();
}
}
/// 将系统架构枚举映射为 LXC 索引架构命名(arm64 -> arm64, x86_64 -> amd64)
static String toLxcArch(DistroArch arch) {
switch (arch) {
case DistroArch.arm64:
return 'arm64';
case DistroArch.x86_64:
return 'amd64';
}
}
/// 动态解析指定发行版在指定镜像源上的最新真实下载 URL
Future<String> resolveDownloadUrl({
required DistroManifestItem item,
required DistroArch arch,
required DistroMirror mirror,
bool forceRefresh = false,
}) async {
// 内置系统直接返回静态资源路径
if (item.isBuiltin) {
return item.packages[arch] ?? '';
}
final spec = item.lxcSpec;
if (spec == null) {
return item.packages[arch] ?? '';
}
final cacheKey = '${mirror.id}:${item.id}:${arch.name}';
if (!forceRefresh && _resolvedUrlCache.containsKey(cacheKey)) {
return _resolvedUrlCache[cacheKey]!;
}
// 1. 获取对应镜像源的 meta/1.0/index-system 索引
final indexContent = await _fetchIndexContent(mirror, forceRefresh: forceRefresh);
// 2. 解析为条目列表
final entries = parseIndex(indexContent);
final targetArch = toLxcArch(arch);
// 3. 匹配符合发行版、版本、变体及 CPU 架构的条目
final matching = entries.where((e) =>
e.distribution.toLowerCase() == spec.distribution.toLowerCase() &&
e.release.toLowerCase() == spec.release.toLowerCase() &&
e.arch.toLowerCase() == targetArch.toLowerCase() &&
e.variant.toLowerCase() == spec.variant.toLowerCase(),
).toList();
if (matching.isEmpty) {
throw HttpException(
'Image not found in mirror ${mirror.name}: ${spec.distribution}/${spec.release}/$targetArch',
);
}
// 4. 按 buildDate 降序排序,取最新一次构建
matching.sort((a, b) => b.buildDate.compareTo(a.buildDate));
final latestEntry = matching.first;
// 5. 组合目标真实 URL
final base = mirror.baseUrl.replaceAll(RegExp(r'/+$'), '');
final relPath = latestEntry.path.replaceAll(RegExp(r'^/+'), '');
final fullUrl = '$base/$relPath' 'rootfs.tar.xz';
_resolvedUrlCache[cacheKey] = fullUrl;
return fullUrl;
}
/// 解析 index-system 纯文本内容为条目列表
static List<DistroIndexEntry> parseIndex(String content) {
final lines = content.split('\n');
final List<DistroIndexEntry> list = [];
for (final line in lines) {
final trimmed = line.trim();
if (trimmed.isEmpty || trimmed.startsWith('#')) continue;
try {
list.add(DistroIndexEntry.fromLine(trimmed));
} catch (_) {}
}
return list;
}
/// 从网络拉取镜像源的 meta/1.0/index-system
Future<String> _fetchIndexContent(DistroMirror mirror, {bool forceRefresh = false}) async {
if (customIndexContent != null) {
return customIndexContent!;
}
final now = DateTime.now();
if (!forceRefresh && _indexContentCache.containsKey(mirror.id)) {
final (cachedAt, text) = _indexContentCache[mirror.id]!;
if (now.difference(cachedAt) < cacheTtl) {
return text;
}
}
HttpClient? client;
try {
client = HttpClient()
..connectionTimeout = const Duration(seconds: 15)
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
final indexUrl = '${mirror.baseUrl.replaceAll(RegExp(r'/+$'), '')}/meta/1.0/index-system';
final request = await client.getUrl(Uri.parse(indexUrl));
final response = await request.close().timeout(const Duration(seconds: 20));
if (response.statusCode != HttpStatus.ok) {
throw HttpException('Failed to fetch mirror index from ${mirror.name}: HTTP ${response.statusCode}');
}
final body = await response.transform(utf8.decoder).join();
_indexContentCache[mirror.id] = (now, body);
return body;
} finally {
client?.close();
}
}
}
+619 -87
View File
@@ -1,9 +1,15 @@
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'package:archive/archive.dart';
import 'dart:isolate';
import 'package:archive/archive_io.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'low_memory_xz_decoder.dart';
final RegExp _paxRecordRegexp = RegExp(r"(\d+) (\w+)=(.*)");
/// 安装进度回调
/// [progress] 0.0 ~ 1.0
@@ -19,16 +25,99 @@ class DistroInstallCancelledException implements Exception {
String toString() => message;
}
class _ExtractIsolateParams {
final String archivePath;
final String targetDirPath;
final SendPort sendPort;
const _ExtractIsolateParams({
required this.archivePath,
required this.targetDirPath,
required this.sendPort,
});
}
/// 流式 TAR 块头部结构解析器
class _TarHeader {
final String filename;
final int mode;
final int fileSize;
final String typeFlag;
final String? nameOfLinkedFile;
_TarHeader({
required this.filename,
required this.mode,
required this.fileSize,
required this.typeFlag,
this.nameOfLinkedFile,
});
static _TarHeader? read(InputStreamBase input) {
if (input.isEOS) return null;
final header = input.readBytes(512);
if (header.length < 512) return null;
final bytes = header.toUint8List();
var allZero = true;
for (var i = 0; i < 512; i++) {
if (bytes[i] != 0) {
allZero = false;
break;
}
}
if (allZero) return null;
String parseString(int offset, int length) {
var end = offset;
final max = offset + length;
while (end < max && bytes[end] != 0) {
end++;
}
return utf8.decode(bytes.sublist(offset, end), allowMalformed: true);
}
int parseInt(int offset, int length) {
final s = parseString(offset, length).trim();
if (s.isEmpty) return 0;
return int.tryParse(s, radix: 8) ?? 0;
}
var filename = parseString(0, 100);
final mode = parseInt(100, 8);
final fileSize = parseInt(124, 12);
final typeFlag = parseString(156, 1);
String? nameOfLinkedFile = parseString(157, 100);
if (nameOfLinkedFile.isEmpty) nameOfLinkedFile = null;
final ustarIndicator = parseString(257, 6);
if (ustarIndicator == 'ustar') {
final filenamePrefix = parseString(345, 155);
if (filenamePrefix.isNotEmpty) {
filename = '$filenamePrefix/$filename';
}
}
return _TarHeader(
filename: filename,
mode: mode,
fileSize: fileSize,
typeFlag: typeFlag,
nameOfLinkedFile: nameOfLinkedFile,
);
}
}
/// Linux 发行版 Rootfs 安装与解压服务
class DistroInstaller {
/// 解压并安装 tar.gz 格式的 Rootfs 到目标目录
/// 从本地文件流式解压并安装 Rootfs(低内存、防卡顿、支持 XZ/GZip/Tar)
///
/// [tarGzBytes] .tar.gz 压缩包字节流
/// [archiveFile] 压缩包文件 (.tar.xz 或 .tar.gz)
/// [targetDir] 目标解压目录 (即容器的 rootfs 路径)
/// [onProgress] 进度回调
/// [isCancelled] 外部取消检查函数
static Future<void> installFromBytes({
required Uint8List tarGzBytes,
static Future<void> installFromFile({
required File archiveFile,
required Directory targetDir,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
@@ -37,88 +126,30 @@ class DistroInstaller {
throw DistroInstallCancelledException();
}
onProgress?.call(0.05, '正在校验与解析系统镜像...');
if (!archiveFile.existsSync()) {
throw ArgumentError('压缩包文件不存在: ${archiveFile.path}');
}
onProgress?.call(0.05, '正在校验与准备解压目录...');
if (!targetDir.existsSync()) {
targetDir.createSync(recursive: true);
}
try {
// 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿)
onProgress?.call(0.15, '正在解压内核与文件系统结构...');
final archive = await compute(_decodeTarGz, tarGzBytes);
// 全平台统一使用低内存流式 Isolate 解压引擎(稳定、确定性进度、低内存、零外部依赖)
await _extractWithDartStreamIsolate(
archiveFile: archiveFile,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
// 2. 写入文件与目录
//
// 权限位必须逐条按 tar 头恢复:dart:io 没有 chmod,而解压本身不会保留
// 可执行位,所以恢复方式是按 mode 分组批量调用 chmod(避免逐文件 fork)。
// 之前这里用 `chmod -R 755` 一把梭,会把 /etc 下的配置文件也变成可执行。
final total = archive.length;
int processed = 0;
final Map<int, List<String>> byMode = <int, List<String>>{};
for (final file in archive) {
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
processed++;
final filename = file.name;
// 避免路径穿越漏洞 (Directory Traversal)
if (filename.contains('..')) continue;
final outPath = p.join(targetDir.path, filename);
if (file.isFile) {
final parentDir = Directory(p.dirname(outPath));
if (!parentDir.existsSync()) {
parentDir.createSync(recursive: true);
}
// 处理符号链接与常规文件
if (file.isSymbolicLink) {
try {
final link = Link(outPath);
if (link.existsSync()) link.deleteSync();
link.createSync(file.nameOfLinkedFile);
} catch (_) {
// Windows 或受限环境降级为写入目标路径文本或忽略
}
} else {
final content = file.content as List<int>;
File(outPath).writeAsBytesSync(content, flush: false);
}
} else {
Directory(outPath).createSync(recursive: true);
}
// 记录 tar 头里的权限位(仅低 12 位有效位)。
// 符号链接必须跳过:chmod 会跟随链接,把目标文件的权限改坏
// (tar 里 symlink 条目的 mode 固定为 0777)。
final mode = file.mode & 0xFFF;
if (mode != 0 && !file.isSymbolicLink) {
byMode.putIfAbsent(mode, () => <String>[]).add(outPath);
}
if (processed % 50 == 0 || processed == total) {
final percent = 0.20 + (processed / total) * 0.70; // 20% ~ 90%
onProgress?.call(percent, '正在释放系统文件 ($processed/$total)...');
}
}
if (!Platform.isWindows) {
await _restoreModes(byMode);
}
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
// 3. 执行系统配置与网络补丁
// 阶段 3:执行系统配置与网络补丁
onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...');
await postInstallConfigure(targetDir);
@@ -134,11 +165,333 @@ class DistroInstaller {
}
}
/// 后台 Isolate 解压 tar.gz
static Archive _decodeTarGz(Uint8List bytes) {
final tarData = GZipDecoder().decodeBytes(bytes);
return TarDecoder().decodeBytes(tarData);
/// 解压并安装内存字节流格式的 Rootfs 到目标目录(兼容已有内置 asset 资源包接口)
static Future<void> installFromBytes({
required Uint8List tarGzBytes,
required Directory targetDir,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
final tempDir = Directory.systemTemp.createTempSync('distro_temp_');
try {
final tempFile = File(p.join(tempDir.path, 'archive.bin'));
await tempFile.writeAsBytes(tarGzBytes, flush: true);
await installFromFile(
archiveFile: tempFile,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
} finally {
if (tempDir.existsSync()) {
try {
tempDir.deleteSync(recursive: true);
} catch (_) {}
}
}
}
/// 在独立后台 Isolate 中执行流式解压与逐文件直接落盘(避免生成几十万对象引发 OOM)
static Future<void> _extractWithDartStreamIsolate({
required File archiveFile,
required Directory targetDir,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
final receivePort = ReceivePort();
final exitPort = ReceivePort();
final completer = Completer<Map<int, List<String>>>();
Isolate? isolate;
Timer? cancelTimer;
try {
isolate = await Isolate.spawn<_ExtractIsolateParams>(
_extractIsolateEntry,
_ExtractIsolateParams(
archivePath: archiveFile.path,
targetDirPath: targetDir.path,
sendPort: receivePort.sendPort,
),
);
isolate.addOnExitListener(exitPort.sendPort);
exitPort.listen((_) {
if (!completer.isCompleted) {
completer.completeError(Exception('解压引擎意外退出'));
}
});
cancelTimer = Timer.periodic(const Duration(milliseconds: 100), (_) {
if (isCancelled?.call() == true) {
isolate?.kill(priority: Isolate.immediate);
if (!completer.isCompleted) {
completer.completeError(DistroInstallCancelledException());
}
}
});
receivePort.listen((message) {
if (message is List) {
final type = message[0] as int;
if (type == 0) {
final prog = message[1] as double;
final msg = message[2] as String;
onProgress?.call(prog, msg);
} else if (type == 1) {
final byMode = (message[1] as Map).cast<int, List<String>>();
if (!completer.isCompleted) {
completer.complete(byMode);
}
} else if (type == 3) {
if (!completer.isCompleted) {
completer.completeError(Exception(message[1].toString()));
}
}
}
});
final byMode = await completer.future;
if (!Platform.isWindows) {
await _restoreModes(byMode);
}
} finally {
cancelTimer?.cancel();
receivePort.close();
exitPort.close();
isolate?.kill(priority: Isolate.immediate);
}
}
/// Isolate 入口:低内存流式解压与逐文件直接落盘
static Future<void> _extractIsolateEntry(_ExtractIsolateParams params) async {
File? tempTarFile;
try {
params.sendPort.send([0, 0.10, '正在读取并解析系统压缩包...']);
final archiveFile = File(params.archivePath);
if (!archiveFile.existsSync()) {
params.sendPort.send([3, '压缩包文件不存在: ${params.archivePath}']);
return;
}
// 1. 检查头部魔数判断文件格式
final raf = archiveFile.openSync(mode: FileMode.read);
final magic = raf.readSync(6);
raf.closeSync();
final isXz = magic.length >= 6 &&
magic[0] == 0xFD &&
magic[1] == 0x37 &&
magic[2] == 0x7A &&
magic[3] == 0x58 &&
magic[4] == 0x5A &&
magic[5] == 0x00;
final isGz = magic.length >= 2 && magic[0] == 0x1F && magic[1] == 0x8B;
final targetDir = Directory(params.targetDirPath);
final tempDir = targetDir.parent.existsSync()
? targetDir.parent
: Directory.systemTemp;
File tarToExtract;
if (isXz) {
params.sendPort.send([0, 0.12, '正在流式解压内核与文件系统结构 (XZ)...']);
tempTarFile = File(p.join(
tempDir.path,
'temp_distro_extract_${DateTime.now().microsecondsSinceEpoch}.tar',
));
if (tempTarFile.existsSync()) {
try {
tempTarFile.deleteSync();
} catch (_) {}
}
final tarSink = tempTarFile.openWrite();
final inputStream = InputFileStream(archiveFile.path);
final archiveSize = archiveFile.lengthSync();
try {
final decoder = LowMemoryXZDecoder();
decoder.decodeToSink(
inputStream,
tarSink,
onProgress: (decompressed, compPos) {
final frac = archiveSize > 0
? (compPos / archiveSize).clamp(0.0, 1.0)
: 0.0;
final prog = 0.12 + frac * 0.38; // 0.12 ~ 0.50
final mb = (decompressed / (1024 * 1024)).toStringAsFixed(1);
params.sendPort.send([0, prog, '正在解压系统文件 ($mb MB)...']);
},
);
} finally {
await tarSink.flush();
await tarSink.close();
await inputStream.close();
}
tarToExtract = tempTarFile;
} else if (isGz) {
params.sendPort.send([0, 0.12, '正在流式解压内核与文件系统结构 (GZip)...']);
tempTarFile = File(p.join(
tempDir.path,
'temp_distro_extract_${DateTime.now().microsecondsSinceEpoch}.tar',
));
if (tempTarFile.existsSync()) {
try {
tempTarFile.deleteSync();
} catch (_) {}
}
final tarSink = tempTarFile.openWrite();
try {
await archiveFile.openRead().transform(gzip.decoder).pipe(tarSink);
} finally {
await tarSink.close();
}
tarToExtract = tempTarFile;
} else {
tarToExtract = archiveFile;
}
// 2. 流式释放 TAR 文件到目标根目录
params.sendPort.send([0, 0.50, '正在释放系统文件...']);
final byMode = await _streamExtractTarFile(
tarFile: tarToExtract,
targetDirPath: params.targetDirPath,
sendPort: params.sendPort,
progressStart: 0.50,
progressEnd: 0.90,
);
params.sendPort.send([1, byMode]);
} catch (e) {
params.sendPort.send([3, e.toString()]);
} finally {
if (tempTarFile != null && tempTarFile.existsSync()) {
try {
tempTarFile.deleteSync();
} catch (_) {}
}
}
}
/// 流式逐条解析 TAR 文件并直接落盘
static Future<Map<int, List<String>>> _streamExtractTarFile({
required File tarFile,
required String targetDirPath,
required SendPort sendPort,
required double progressStart,
required double progressEnd,
}) async {
final input = InputFileStream(tarFile.path);
final byMode = <int, List<String>>{};
final totalLen = tarFile.lengthSync();
String? nextName;
String? nextLinkName;
int processed = 0;
try {
while (!input.isEOS) {
final th = _TarHeader.read(input);
if (th == null) break;
if (th.filename == '././@LongLink') {
final contentBytes = input.readBytes(th.fileSize).toUint8List();
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
final text = utf8.decode(contentBytes, allowMalformed: true).split('\x00').first;
if (th.typeFlag == 'K') {
nextLinkName = text;
} else {
nextName = text;
}
continue;
}
if (th.typeFlag == 'g' || th.typeFlag == 'x') {
// PAX Header
try {
final paxBytes = input.readBytes(th.fileSize).toUint8List();
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
final headerContent = utf8.decode(paxBytes, allowMalformed: true);
for (final line in headerContent.split('\n')) {
final match = _paxRecordRegexp.firstMatch(line);
if (match != null) {
final k = match.group(2);
final v = match.group(3);
if (k == 'path' && v != null) nextName = v;
if (k == 'linkpath' && v != null) nextLinkName = v;
}
}
} catch (_) {}
continue;
}
final filename = nextName ?? th.filename;
nextName = null;
final linkName = nextLinkName ?? th.nameOfLinkedFile;
nextLinkName = null;
if (filename.contains('..')) {
if (th.fileSize > 0) {
input.skip(th.fileSize);
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
}
continue;
}
final outPath = p.join(targetDirPath, filename);
if (th.typeFlag == '5' || th.filename.endsWith('/')) {
final d = Directory(outPath);
if (!d.existsSync()) d.createSync(recursive: true);
} else if ((th.typeFlag == '2' || th.typeFlag == '1') && linkName != null) {
try {
final parent = Directory(p.dirname(outPath));
if (!parent.existsSync()) parent.createSync(recursive: true);
final link = Link(outPath);
if (link.existsSync()) link.deleteSync();
link.createSync(linkName);
} catch (_) {}
} else {
final parent = Directory(p.dirname(outPath));
if (!parent.existsSync()) parent.createSync(recursive: true);
final f = File(outPath);
final sink = f.openWrite();
var remaining = th.fileSize;
while (remaining > 0) {
final chunk = remaining < 65536 ? remaining : 65536;
sink.add(input.readBytes(chunk).toUint8List());
remaining -= chunk;
}
await sink.flush();
await sink.close();
final remainder = th.fileSize % 512;
if (remainder != 0) input.skip(512 - remainder);
}
final mode = th.mode & 0xFFF;
if (mode != 0 && th.typeFlag != '2') {
byMode.putIfAbsent(mode, () => <String>[]).add(outPath);
}
processed++;
if (processed % 150 == 0) {
final fraction = totalLen > 0 ? (input.position / totalLen).clamp(0.0, 1.0) : 0.0;
final prog = progressStart + fraction * (progressEnd - progressStart);
sendPort.send([0, prog, '正在释放系统文件 ($processed)...']);
}
}
} finally {
await input.close();
}
return byMode;
}
/// 按 tar 头恢复权限位(dart:io 无 chmod,按 mode 分组批量调用,避免逐文件 fork)
static Future<void> _restoreModes(Map<int, List<String>> byMode) async {
@@ -197,34 +550,171 @@ class DistroInstaller {
debugPrint('[DistroInstaller] 写入 hosts 失败: $e');
}
// 3. 配置 Alpine apk 软件源镜像(使用阿里云高速稳定镜像)
// 3. 配置软件源镜像(按发行版自动适配,国内高速镜像)
final apkDir = Directory(p.join(etcDir.path, 'apk'));
if (apkDir.existsSync()) {
// 3.1 Alpine apk 软件源镜像(使用阿里云高速镜像,自适应主版本号)
var alpineVer = 'v3.20';
final alpineRel = File(p.join(etcDir.path, 'alpine-release'));
if (alpineRel.existsSync()) {
try {
final relStr = alpineRel.readAsStringSync().trim();
final match = RegExp(r'^(\d+\.\d+)').firstMatch(relStr);
if (match != null) {
alpineVer = 'v${match.group(1)}';
}
} catch (_) {}
}
final repoFile = File(p.join(apkDir.path, 'repositories'));
try {
repoFile.writeAsStringSync(
'https://mirrors.aliyun.com/alpine/v3.20/main\n'
'https://mirrors.aliyun.com/alpine/v3.20/community\n',
'https://mirrors.aliyun.com/alpine/$alpineVer/main\n'
'https://mirrors.aliyun.com/alpine/$alpineVer/community\n',
);
} catch (e) {
debugPrint('[DistroInstaller] 写入 repositories 失败: $e');
}
}
// 4. 确保 /workspace 挂载点目录存在
// 4. 自动部署根证书(解决最小化 Linux 发行版缺少 ca-certificates 导致 https 证书验证失败)
await ensureCaCertificates(rootfsDir);
final aptDir = Directory(p.join(etcDir.path, 'apt'));
if (aptDir.existsSync()) {
final sourcesD = Directory(p.join(aptDir.path, 'sources.list.d'));
final ubuntuSources = File(p.join(sourcesD.path, 'ubuntu.sources'));
final isUbuntu = ubuntuSources.existsSync() ||
(File(p.join(etcDir.path, 'os-release')).existsSync() &&
File(p.join(etcDir.path, 'os-release')).readAsStringSync().toLowerCase().contains('ubuntu'));
if (isUbuntu) {
// 3.2 Ubuntu deb822 源配置(清华大学高速镜像)
if (!sourcesD.existsSync()) sourcesD.createSync(recursive: true);
try {
final isArm = (Abi.current() == Abi.androidArm64 || Abi.current() == Abi.linuxArm64);
final mirrorUri = isArm
? 'https://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/'
: 'https://mirrors.tuna.tsinghua.edu.cn/ubuntu/';
ubuntuSources.writeAsStringSync(
'Types: deb\n'
'URIs: $mirrorUri\n'
'Suites: noble noble-updates noble-backports noble-security\n'
'Components: main universe restricted multiverse\n'
'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n',
);
} catch (e) {
debugPrint('[DistroInstaller] 写入 ubuntu.sources 失败: $e');
}
} else {
// 3.3 Debian 源配置(清华大学高速镜像)
final debianSources = File(p.join(sourcesD.path, 'debian.sources'));
final sourcesList = File(p.join(aptDir.path, 'sources.list'));
try {
sourcesList.writeAsStringSync(
'deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware\n'
'deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware\n'
'deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware\n'
'deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware\n',
);
if (debianSources.existsSync()) {
debianSources.writeAsStringSync(
'Types: deb\n'
'URIs: https://mirrors.tuna.tsinghua.edu.cn/debian/\n'
'Suites: bookworm bookworm-updates bookworm-backports\n'
'Components: main contrib non-free non-free-firmware\n'
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg\n'
'\n'
'Types: deb\n'
'URIs: https://mirrors.tuna.tsinghua.edu.cn/debian-security\n'
'Suites: bookworm-security\n'
'Components: main contrib non-free non-free-firmware\n'
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg\n',
);
}
} catch (e) {
debugPrint('[DistroInstaller] 写入 debian sources 失败: $e');
}
}
}
// 3.4 Arch Linux pacman 源配置(清华大学高速镜像)
final pacmanDir = Directory(p.join(etcDir.path, 'pacman.d'));
if (pacmanDir.existsSync()) {
final mirrorlist = File(p.join(pacmanDir.path, 'mirrorlist'));
try {
mirrorlist.writeAsStringSync(
'Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/\$repo/os/\$arch\n'
'Server = https://mirrors.aliyun.com/archlinux/\$repo/os/\$arch\n',
);
} catch (e) {
debugPrint('[DistroInstaller] 写入 Arch mirrorlist 失败: $e');
}
}
// 3.5 Fedora yum/dnf 源配置(清华大学高速镜像)
final yumDir = Directory(p.join(etcDir.path, 'yum.repos.d'));
if (yumDir.existsSync()) {
final fedoraRepo = File(p.join(yumDir.path, 'fedora.repo'));
if (fedoraRepo.existsSync()) {
try {
var content = fedoraRepo.readAsStringSync();
content = content.replaceAll('metalink=', '#metalink=');
content = content.replaceAll(
'#baseurl=http://download.example/pub/fedora/linux/',
'baseurl=https://mirrors.tuna.tsinghua.edu.cn/fedora/',
);
fedoraRepo.writeAsStringSync(content);
} catch (e) {
debugPrint('[DistroInstaller] 写入 Fedora repo 失败: $e');
}
}
}
// 5. 确保 /workspace 挂载点目录存在
final workspaceDir = Directory(p.join(rootfsDir.path, 'workspace'));
if (!workspaceDir.existsSync()) {
workspaceDir.createSync(recursive: true);
}
// 5. 确保 /tmp 目录存在
// 6. 确保 /tmp 目录存在
final tmpDir = Directory(p.join(rootfsDir.path, 'tmp'));
if (!tmpDir.existsSync()) {
tmpDir.createSync(recursive: true);
}
// 6. 部署容器修复 Shim(libfix_seccomp.so)
// 7. 部署容器修复 Shim(libfix_seccomp.so)
await ensureSeccompShim(rootfsDir);
// 8. 自动配置 Java 运行时动态链接路径
await ensureJavaConfiguration(rootfsDir);
}
/// 自动部署标准 SSL CA 证书链(让 APT / Curl / Git 默认支持 HTTPS)
static Future<void> ensureCaCertificates(Directory rootfsDir) async {
try {
final certsDir = Directory(p.join(rootfsDir.path, 'etc', 'ssl', 'certs'));
if (!certsDir.existsSync()) {
certsDir.createSync(recursive: true);
}
final targetCert = File(p.join(certsDir.path, 'ca-certificates.crt'));
if (!targetCert.existsSync() || targetCert.lengthSync() == 0) {
final byteData = await rootBundle.load('assets/certs/ca-certificates.crt');
final bytes = byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes);
await targetCert.writeAsBytes(bytes, flush: true);
// 建立标准符号链接以兼容 OpenSSL/GnuTLS 默认寻找路径
final etcSslDir = Directory(p.join(rootfsDir.path, 'etc', 'ssl'));
final certPem = Link(p.join(etcSslDir.path, 'cert.pem'));
if (!certPem.existsSync()) {
try {
certPem.createSync('certs/ca-certificates.crt');
} catch (_) {}
}
debugPrint('[DistroInstaller] 成功注入根证书链: ${targetCert.path}');
}
} catch (e) {
debugPrint('[DistroInstaller] 注入根证书链异常 (非阻塞): $e');
}
}
/// 部署容器修复 Shim(libfix_seccomp.so)
@@ -237,8 +727,10 @@ class DistroInstaller {
/// 传统 syscall 返回 ENOSYS,而 musl 在有这些调用的架构上优先用它们。
static Future<void> ensureSeccompShim(Directory rootfsDir) async {
final libDir = Directory(p.join(rootfsDir.path, 'lib'));
if (!libDir.existsSync()) {
if (!libDir.existsSync() && !FileSystemEntity.isLinkSync(libDir.path)) {
try {
libDir.createSync(recursive: true);
} catch (_) {}
}
final targetShim = File(p.join(libDir.path, 'libfix_seccomp.so'));
@@ -272,4 +764,44 @@ class DistroInstaller {
debugPrint('[DistroInstaller] 部署 SECCOMP Shim 失败: $e');
}
}
/// 自动探测并适配 OpenJDK 运行环境(解决 Debian/Ubuntu 等发行版下 /usr/bin/java
/// 符号链接调用时找不到 libjli.so / libjvm.so 的问题)
static Future<void> ensureJavaConfiguration(Directory rootfsDir) async {
try {
final jvmDir = Directory(p.join(rootfsDir.path, 'usr', 'lib', 'jvm'));
if (!jvmDir.existsSync()) return;
final javaConfLines = <String>[];
final jvmEntries = jvmDir.listSync();
for (final entry in jvmEntries) {
if (entry is Directory) {
final guestJvmBase = '/usr/lib/jvm/${p.basename(entry.path)}';
final libDir = Directory(p.join(entry.path, 'lib'));
if (libDir.existsSync()) {
javaConfLines.add('$guestJvmBase/lib');
final serverDir = Directory(p.join(libDir.path, 'server'));
if (serverDir.existsSync()) {
javaConfLines.add('$guestJvmBase/lib/server');
}
}
}
}
if (javaConfLines.isNotEmpty) {
final ldConfD = Directory(p.join(rootfsDir.path, 'etc', 'ld.so.conf.d'));
if (!ldConfD.existsSync()) {
ldConfD.createSync(recursive: true);
}
final javaConfFile = File(p.join(ldConfD.path, 'java.conf'));
final newContent = '${javaConfLines.join('\n')}\n';
if (!javaConfFile.existsSync() || javaConfFile.readAsStringSync() != newContent) {
javaConfFile.writeAsStringSync(newContent);
debugPrint('[DistroInstaller] 自动配置 /etc/ld.so.conf.d/java.conf');
}
}
} catch (e) {
debugPrint('[DistroInstaller] 配置 Java ld.so 失败 (非阻塞): $e');
}
}
}
+339 -15
View File
@@ -4,7 +4,7 @@ import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../models/distro_info.dart';
import '../models/distro_manifest.dart';
import 'distro_installer.dart';
/// 容器启动配置数据
@@ -35,6 +35,16 @@ class ProotLaunchConfig {
}
}
/// Linux 发行版家族分类(用于包管理器与工具链自动适配)
enum DistroFamily {
alpine,
ubuntu,
debian,
arch,
fedora,
unknown,
}
/// Linux 发行版与多系统实例管理器服务(单例模式,易扩展)
class DistroManager {
static final DistroManager _instance = DistroManager._internal();
@@ -104,6 +114,55 @@ class DistroManager {
return hasEtc && hasBin;
}
/// 自动探测指定已安装系统所属的发行版家族(Alpine / Ubuntu / Debian / Arch / Fedora / Unknown)
Future<DistroFamily> detectDistroFamily(String systemName) async {
if (systemName == 'host') return DistroFamily.unknown;
final rootDir = await getSystemRootDir(systemName);
if (!rootDir.existsSync()) return DistroFamily.unknown;
final etcDir = Directory(p.join(rootDir.path, 'etc'));
if (!etcDir.existsSync()) return DistroFamily.unknown;
// 1. Alpine Linux (apk / alpine-release)
if (Directory(p.join(etcDir.path, 'apk')).existsSync() ||
File(p.join(etcDir.path, 'alpine-release')).existsSync() ||
File(p.join(rootDir.path, 'sbin', 'apk')).existsSync()) {
return DistroFamily.alpine;
}
// 2. Ubuntu 与 Debian (apt / dpkg)
final aptDir = Directory(p.join(etcDir.path, 'apt'));
if (aptDir.existsSync() || File(p.join(rootDir.path, 'usr', 'bin', 'apt-get')).existsSync()) {
final ubuntuSources = File(p.join(aptDir.path, 'sources.list.d', 'ubuntu.sources'));
final osRelease = File(p.join(etcDir.path, 'os-release'));
var isUbuntu = ubuntuSources.existsSync();
if (!isUbuntu && osRelease.existsSync()) {
try {
isUbuntu = osRelease.readAsStringSync().toLowerCase().contains('ubuntu');
} catch (_) {}
}
return isUbuntu ? DistroFamily.ubuntu : DistroFamily.debian;
}
// 3. Arch Linux (pacman)
if (Directory(p.join(etcDir.path, 'pacman.d')).existsSync() ||
File(p.join(etcDir.path, 'arch-release')).existsSync() ||
File(p.join(rootDir.path, 'usr', 'bin', 'pacman')).existsSync()) {
return DistroFamily.arch;
}
// 4. Fedora (dnf / yum / fedora-release)
if (Directory(p.join(etcDir.path, 'yum.repos.d')).existsSync() ||
File(p.join(etcDir.path, 'fedora-release')).existsSync() ||
File(p.join(rootDir.path, 'usr', 'bin', 'dnf')).existsSync()) {
return DistroFamily.fedora;
}
// 5. 其他未识别的自定义系统
return DistroFamily.unknown;
}
/// 校验系统名称是否合法且未被占用
Future<void> validateSystemName(String systemName) async {
final trimmed = systemName.trim();
@@ -122,18 +181,18 @@ class DistroManager {
}
}
/// 从应用内置资源导入 Alpine Linux 系统实例
/// 从应用内置资源导入 Ubuntu 24.04 Linux 系统实例
///
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
Future<void> importBuiltinAlpine({
/// [systemName] 系统名称(默认为 'ubuntu',同一个 rootfs 包可创建多个系统)
Future<void> importBuiltinUbuntu({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
final assetPath = DistroInfo.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置系统资源包...');
final assetPath = DistroRepository.builtinUbuntuAssetPath;
onProgress?.call(0.02, '正在读取应用内置 Ubuntu 系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
@@ -147,7 +206,32 @@ class DistroManager {
);
}
/// 从用户本地指定的 .tar.gz 压缩包导入外部系统实例
/// 从应用内置资源导入 Alpine Linux 系统实例(保留备用)
///
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
final assetPath = DistroRepository.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置 Alpine 系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 从用户本地指定的 .tar.gz / .tar.xz 压缩包导入外部系统实例
Future<void> importFromCustomTarGz({
required String systemName,
required File tarGzFile,
@@ -160,13 +244,10 @@ class DistroManager {
throw ArgumentError('所选压缩包文件不存在: ${tarGzFile.path}');
}
onProgress?.call(0.02, '正在读取外部系统压缩包...');
final bytes = await tarGzFile.readAsBytes();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
await DistroInstaller.installFromFile(
archiveFile: tarGzFile,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
@@ -261,12 +342,13 @@ class DistroManager {
? workspacePath
: Directory.current.path;
final args = customCommand != null ? ['-c', customCommand] : <String>[];
final args = customCommand != null ? ['-c', customCommand] : <String>['-i'];
return ProotLaunchConfig(
executable: '/system/bin/sh',
arguments: args,
environment: {
'TERM': 'xterm-256color',
'SHELL': '/system/bin/sh',
},
workingDirectory: initialDir,
);
@@ -276,11 +358,23 @@ class DistroManager {
final rootDir = await getSystemRootDir(systemName);
final nativeDir = await getNativeLibraryDir();
final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath;
const targetShell = '/bin/sh';
final targetShell = _resolveTargetShell(rootDir);
// 确保容器内 DNS 配置存在(对标 proot-distro,保证网络连通与 apk/curl 正常解析)
await _ensureGuestDns(rootDir);
// 清理此前异常中断留下的陈旧锁文件(如 /etc/group.lock,防止 groupadd/useradd 报错)
_cleanStaleLocks(rootDir);
// 确保 Android 宿主特权/辅助组映射与 .hushlogin 存在(解决 groups: cannot find name for group ID 警告)
await _ensureHostGroups(rootDir);
// 确保容器内具备标准 SSL CA 证书(解决 APT/Git/Curl 访问 HTTPS 时的证书校验失败)
await DistroInstaller.ensureCaCertificates(rootDir);
// 确保 Java 运行时动态链接配置就绪(解决 /usr/bin/java 符号链接找不到 libjli.so)
await DistroInstaller.ensureJavaConfiguration(rootDir);
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
final shmDir = await _ensureShmDir(systemName);
@@ -341,13 +435,41 @@ class DistroManager {
final shimFile = File(p.join(rootDir.path, 'lib', 'libfix_seccomp.so'));
final hasShim = shimFile.existsSync();
// 自动检测并注入 JAVA_HOME
String? guestJavaHome;
final jvmDir = Directory(p.join(rootDir.path, 'usr', 'lib', 'jvm'));
if (jvmDir.existsSync()) {
try {
final defaultJava = Directory(p.join(jvmDir.path, 'default-java'));
if (defaultJava.existsSync()) {
guestJavaHome = '/usr/lib/jvm/default-java';
} else {
final entries = jvmDir.listSync().whereType<Directory>().toList();
if (entries.isNotEmpty) {
entries.sort((a, b) => p.basename(b.path).compareTo(p.basename(a.path)));
final selected = entries.firstWhere(
(d) => p.basename(d.path).startsWith('java-'),
orElse: () => entries.first,
);
guestJavaHome = '/usr/lib/jvm/${p.basename(selected.path)}';
}
}
} catch (_) {}
}
final guestEnvArgs = <String>[
'/usr/bin/env',
'-i',
'HOME=/root',
'USER=root',
'SHELL=$targetShell',
'TERM=xterm-256color',
'COLORTERM=truecolor',
'LANG=C.UTF-8',
if (guestJavaHome != null) 'JAVA_HOME=$guestJavaHome',
if (guestJavaHome != null)
'PATH=$guestJavaHome/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
else
'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
if (hasShim) 'LD_PRELOAD=/lib/libfix_seccomp.so',
];
@@ -358,14 +480,20 @@ class DistroManager {
if (customCommand != null && customCommand.isNotEmpty) {
args.addAll([targetShell, '-c', customCommand]);
} else {
args.addAll([targetShell, '-l']);
args.addAll([targetShell, '-l', '-i']);
}
final env = <String, String>{
'HOME': '/root',
'USER': 'root',
'SHELL': targetShell,
'TERM': 'xterm-256color',
'COLORTERM': 'truecolor',
'LANG': 'C.UTF-8',
if (guestJavaHome != null) 'JAVA_HOME': guestJavaHome,
if (guestJavaHome != null)
'PATH': '$guestJavaHome/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
else
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
'TMPDIR': tmpPath,
'PROOT_TMP_DIR': tmpPath,
@@ -469,4 +597,200 @@ class DistroManager {
return null;
}
}
/// 智能选择不同 Linux 发行版最适配的交互式 Shell:
/// 1. 优先读取 /etc/passwd 中 root 用户指定的默认登录 Shell(如用户自行切换了 zsh/fish);
/// 2. 若配置为 /bin/sh,但在存在 GNU Readline 支持的更好交互 Shell(如 /bin/bash)时优先升级至 bash,
/// 彻底解决 Ubuntu/Debian 等发行版 /bin/sh (dash) 缺少行编辑与 Readline 支持的问题;
/// 3. 若系统中无 bash(如原版最小化 Alpine),则使用 /bin/ash 或 /bin/sh;
/// 4. 支持 /usr/bin/bash、/usr/bin/zsh 等现代 Linux UsrMerge 单一根目录结构。
String _resolveTargetShell(Directory rootDir) {
String? rootPasswdShell;
final passwdFile = File(p.join(rootDir.path, 'etc', 'passwd'));
if (passwdFile.existsSync()) {
try {
final lines = passwdFile.readAsLinesSync();
for (final line in lines) {
if (line.startsWith('root:')) {
final parts = line.split(':');
if (parts.length >= 7) {
final sh = parts[6].trim();
if (sh.isNotEmpty) {
rootPasswdShell = sh;
break;
}
}
}
}
} catch (_) {}
}
final hasBash = File(p.join(rootDir.path, 'bin', 'bash')).existsSync() ||
File(p.join(rootDir.path, 'usr', 'bin', 'bash')).existsSync();
final hasZsh = File(p.join(rootDir.path, 'bin', 'zsh')).existsSync() ||
File(p.join(rootDir.path, 'usr', 'bin', 'zsh')).existsSync();
final hasAsh = File(p.join(rootDir.path, 'bin', 'ash')).existsSync() ||
File(p.join(rootDir.path, 'usr', 'bin', 'ash')).existsSync();
// 如果 passwd 里配置了非 /bin/sh 的具体 shell(如 /bin/bash, /bin/zsh, /bin/ash, /usr/bin/fish)且物理文件存在,遵从系统配置
if (rootPasswdShell != null &&
rootPasswdShell != '/bin/sh' &&
rootPasswdShell != '/usr/bin/sh') {
final shellRel = rootPasswdShell.startsWith('/') ? rootPasswdShell.substring(1) : rootPasswdShell;
if (File(p.join(rootDir.path, shellRel)).existsSync()) {
return rootPasswdShell;
}
}
// 默认回退链:bash (Ubuntu/Debian/Arch/Fedora) -> zsh -> ash (Alpine) -> sh
if (hasBash) {
return '/bin/bash';
} else if (hasZsh) {
return '/bin/zsh';
} else if (hasAsh) {
return '/bin/ash';
}
return '/bin/sh';
}
/// 保证 Android 宿主分配给当前 App 进程的所有辅助 GID 在容器 /etc/group 中均有注册,
/// 并在 /root 下创建 .hushlogin,彻底消除 login 时输出
/// "groups: cannot find name for group ID XXX" 等警告。
Future<void> _ensureHostGroups(Directory rootDir) async {
try {
if (!rootDir.existsSync()) return;
final etcDir = Directory(p.join(rootDir.path, 'etc'));
if (!etcDir.existsSync()) {
try {
etcDir.createSync(recursive: true);
} catch (_) {}
}
final groupFile = File(p.join(etcDir.path, 'group'));
final existingGids = <int>{};
String existingContent = '';
if (groupFile.existsSync()) {
existingContent = groupFile.readAsStringSync();
for (final line in existingContent.split('\n')) {
final parts = line.split(':');
if (parts.length >= 3) {
final gid = int.tryParse(parts[2].trim());
if (gid != null) existingGids.add(gid);
}
}
}
// 获取宿主当前进程拥有的所有 GID
final targetGids = <int>{
// 常见 Android 特权/网络与存储辅助 GID
1015, // sdcard_rw
1028, // sdcard_r
1077, // ext_data_rw
3003, // inet
3004, // net_raw
3005, // net_admin
9997, // everybody
};
// 从 /proc/self/status 动态提取当前真实附加的 Groups
final procStatus = File('/proc/self/status');
if (procStatus.existsSync()) {
try {
final lines = procStatus.readAsLinesSync();
for (final line in lines) {
if (line.startsWith('Groups:')) {
final gids = line.substring(7).trim().split(RegExp(r'\s+'));
for (final s in gids) {
final val = int.tryParse(s);
if (val != null) targetGids.add(val);
}
}
}
} catch (_) {}
}
final buffer = StringBuffer();
for (final gid in targetGids) {
if (!existingGids.contains(gid)) {
final groupName = _androidAidGroupName(gid);
buffer.writeln('$groupName:x:$gid:');
}
}
// 保证常见系统服务所需的用户组存在(如 dbus 所需的 messagebus GID 101)
if (!existingGids.contains(101) && !existingContent.contains('messagebus:')) {
buffer.writeln('messagebus:x:101:');
}
if (buffer.isNotEmpty) {
if (!groupFile.existsSync()) {
groupFile.writeAsStringSync(buffer.toString());
} else {
final separator = existingContent.endsWith('\n') || existingContent.isEmpty ? '' : '\n';
groupFile.writeAsStringSync('$separator${buffer.toString()}', mode: FileMode.append);
}
}
// 静默模式:创建 /root/.hushlogin 屏蔽 motd / 登录杂乱信息
final rootHome = Directory(p.join(rootDir.path, 'root'));
if (!rootHome.existsSync()) {
try {
rootHome.createSync(recursive: true);
} catch (_) {}
}
final hushFile = File(p.join(rootHome.path, '.hushlogin'));
if (!hushFile.existsSync()) {
try {
hushFile.createSync();
} catch (_) {}
}
} catch (e) {
debugPrint('配置容器辅助用户组失败 (非阻塞): $e');
}
}
/// 清理此前异常崩溃或中断留下的陈旧锁文件(防止 groupadd/useradd 等报 /etc/*.lock 锁占用或找不到)
void _cleanStaleLocks(Directory rootDir) {
try {
final etcDir = Directory(p.join(rootDir.path, 'etc'));
if (etcDir.existsSync()) {
for (final entry in etcDir.listSync(followLinks: false)) {
final name = p.basename(entry.path);
if (name.endsWith('.lock') ||
name.startsWith('group.') ||
name.startsWith('passwd.') ||
name.startsWith('shadow.') ||
name.startsWith('gshadow.')) {
try {
entry.deleteSync(recursive: true);
debugPrint('[DistroManager] 清理陈旧锁文件: ${entry.path}');
} catch (_) {}
}
}
}
} catch (e) {
debugPrint('[DistroManager] 清理陈旧锁文件异常 (非阻塞): $e');
}
}
static String _androidAidGroupName(int gid) {
switch (gid) {
case 1015:
return 'aid_sdcard_rw';
case 1028:
return 'aid_sdcard_r';
case 1077:
return 'aid_ext_data_rw';
case 3003:
return 'aid_inet';
case 3004:
return 'aid_net_raw';
case 3005:
return 'aid_net_admin';
case 9997:
return 'aid_everybody';
default:
return 'aid_$gid';
}
}
}
+179
View File
@@ -0,0 +1,179 @@
import 'dart:io';
import 'package:archive/archive_io.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
/// 软件内部私有存储项目管理服务 (files/projects)
class InternalProjectService {
static final InternalProjectService instance = InternalProjectService._();
factory InternalProjectService() => instance;
InternalProjectService._();
/// 自定义项目存储根目录(主要用于单元测试与隔离环境)
@visibleForTesting
Directory? customProjectsDir;
Directory? _cachedProjectsDir;
/// 判断指定路径是否为内部存储项目路径 (`files/projects/<projectName>`)
bool isInternalProject(String? projectPath) {
if (projectPath == null || projectPath.trim().isEmpty) return false;
final cleanPath = p.normalize(projectPath.trim());
if (customProjectsDir != null) {
final customParent = p.normalize(customProjectsDir!.path);
return p.equals(p.dirname(cleanPath), customParent);
}
if (_cachedProjectsDir != null) {
final cachedParent = p.normalize(_cachedProjectsDir!.path);
return p.equals(p.dirname(cleanPath), cachedParent);
}
final parentDir = p.normalize(p.dirname(cleanPath));
final parts = p.split(parentDir);
if (parts.length >= 2 &&
parts[parts.length - 2] == 'files' &&
parts[parts.length - 1] == 'projects') {
return true;
}
return false;
}
/// 获取软件内部存储的项目基础目录: `files/projects`
Future<Directory> getProjectsDirectory() async {
if (customProjectsDir != null) {
if (!customProjectsDir!.existsSync()) {
customProjectsDir!.createSync(recursive: true);
}
return customProjectsDir!;
}
if (_cachedProjectsDir != null) {
if (!_cachedProjectsDir!.existsSync()) {
_cachedProjectsDir!.createSync(recursive: true);
}
return _cachedProjectsDir!;
}
final appDir = await getApplicationSupportDirectory();
// Android 下 getApplicationSupportDirectory 对应 .../files
// 若路径已以 files 结尾,则直接拼接 projects;否则拼接 files/projects 保持规范一致
final baseDir = p.basename(appDir.path) == 'files'
? appDir.path
: p.join(appDir.path, 'files');
final projectsDir = Directory(p.join(baseDir, 'projects'));
if (!projectsDir.existsSync()) {
projectsDir.createSync(recursive: true);
}
_cachedProjectsDir = projectsDir;
return projectsDir;
}
/// 获取所有已创建的内部项目列表(按文件夹名称升序排列)
Future<List<Directory>> listProjects() async {
final dir = await getProjectsDirectory();
if (!dir.existsSync()) {
return [];
}
try {
final entities = dir.listSync(followLinks: false);
final projects = entities.whereType<Directory>().toList();
projects.sort((a, b) => p
.basename(a.path)
.toLowerCase()
.compareTo(p.basename(b.path).toLowerCase()));
return projects;
} catch (e) {
debugPrint('获取内部项目列表失败: $e');
return [];
}
}
/// 检查指定项目名称是否已存在
Future<bool> projectExists(String name) async {
final dir = await getProjectsDirectory();
final targetDir = Directory(p.join(dir.path, name.trim()));
return targetDir.existsSync();
}
/// 在 `files/projects` 下新建一个项目文件夹
Future<Directory> createProject(String name) async {
final trimmedName = name.trim();
if (trimmedName.isEmpty) {
throw const FileSystemException('项目名称不能为空');
}
final dir = await getProjectsDirectory();
final projectDir = Directory(p.join(dir.path, trimmedName));
if (projectDir.existsSync()) {
throw FileSystemException('同名项目已存在', projectDir.path);
}
projectDir.createSync(recursive: true);
return projectDir;
}
/// 重命名指定的项目文件夹
Future<Directory> renameProject(Directory projectDir, String newName) async {
final trimmedName = newName.trim();
if (trimmedName.isEmpty) {
throw const FileSystemException('项目名称不能为空');
}
final parent = projectDir.parent;
final newDir = Directory(p.join(parent.path, trimmedName));
if (p.normalize(projectDir.path) == p.normalize(newDir.path)) {
return projectDir;
}
if (newDir.existsSync()) {
throw FileSystemException('同名项目已存在', newDir.path);
}
return projectDir.renameSync(newDir.path);
}
/// 递归删除项目文件夹
Future<void> deleteProject(Directory projectDir) async {
if (projectDir.existsSync()) {
projectDir.deleteSync(recursive: true);
}
}
/// 从外部压缩文件解压导入为内部项目 (`files/projects/<projectName>`)
Future<Directory> importProjectFromArchive(String archivePath, String projectName) async {
final trimmedName = projectName.trim();
if (trimmedName.isEmpty) {
throw const FileSystemException('项目名称不能为空');
}
final dir = await getProjectsDirectory();
final projectDir = Directory(p.join(dir.path, trimmedName));
if (projectDir.existsSync()) {
throw FileSystemException('同名项目已存在', projectDir.path);
}
final archiveFile = File(archivePath);
if (!archiveFile.existsSync()) {
throw FileSystemException('压缩包文件不存在', archivePath);
}
projectDir.createSync(recursive: true);
try {
await extractFileToDisk(archivePath, projectDir.path);
return projectDir;
} catch (e) {
if (projectDir.existsSync()) {
try {
projectDir.deleteSync(recursive: true);
} catch (_) {}
}
rethrow;
}
}
}
+809
View File
@@ -0,0 +1,809 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:archive/archive.dart';
/// 低内存 XZ 流式解压器
///
/// 解决 package:archive 在解码大于 10MB 的 XZ 压缩包时 LZMA 字典无限增长、
/// 频繁触发全量数组复制导致内存爆炸 (OOM) 与卡死的致命缺陷。
///
/// 本解码器采用固定大小环形滑动窗口(Circular Ring Buffer),内存占用严格恒定在
/// 字典大小(如 Debian rootfs 仅需 8MB),并将解压数据分块直接流式写入输出文件 Sink,
/// 内存开销从原版的数百 GB 累计分配降至仅 ~10MB。
class LowMemoryXZDecoder {
final LowMemoryLzmaDecoder decoder = LowMemoryLzmaDecoder();
int streamFlags = 0;
/// 流式解压 XZ 输入流并输出到 [outputSink]
void decodeToSink(
InputStreamBase input,
IOSink outputSink, {
void Function(int bytesDecompressed, int compressedPosition)? onProgress,
bool Function()? isCancelled,
}) {
var totalDecompressed = 0;
while (!input.isEOS) {
if (isCancelled?.call() == true) return;
// 跳过流间或流末尾的 4 字节对齐填充(NULL 字节)
while (!input.isEOS && input.peekBytes(1).readByte() == 0) {
input.skip(1);
}
if (input.isEOS) break;
_readStreamHeader(input);
while (true) {
if (isCancelled?.call() == true) return;
final blockHeader = input.peekBytes(1).readByte();
if (blockHeader == 0) {
// 流索引与流尾部
final indexSize = _readStreamIndex(input);
_readStreamFooter(input, indexSize);
break; // 当前流结束
}
final blockLength = (blockHeader + 1) * 4;
_readBlock(input, blockLength, outputSink, (bytes) {
totalDecompressed += bytes;
onProgress?.call(totalDecompressed, input.position);
}, isCancelled);
}
}
}
void _readStreamHeader(InputStreamBase input) {
final magic = input.readBytes(6).toUint8List();
if (magic[0] != 253 ||
magic[1] != 55 ||
magic[2] != 122 ||
magic[3] != 88 ||
magic[4] != 90 ||
magic[5] != 0) {
throw ArchiveException('Invalid XZ stream header signature');
}
final header = input.readBytes(2);
if (header.readByte() != 0) {
throw ArchiveException('Invalid stream flags');
}
streamFlags = header.readByte();
header.reset();
final crc = input.readUint32();
if (getCrc32(header.toUint8List()) != crc) {
throw ArchiveException('Invalid stream header CRC checksum');
}
}
int _readMultibyteInteger(InputStreamBase input) {
var val = 0;
var shift = 0;
while (true) {
final b = input.readByte();
val |= (b & 0x7f) << shift;
if ((b & 0x80) == 0) break;
shift += 7;
}
return val;
}
int _readPadding(InputStreamBase input) {
var count = 0;
while (!input.isEOS && (input.position % 4 != 0)) {
if (input.readByte() != 0) {
throw ArchiveException('Invalid padding byte');
}
count++;
}
return count;
}
void _readBlock(
InputStreamBase input,
int headerLength,
IOSink sink,
void Function(int bytes) onChunk,
bool Function()? isCancelled,
) {
final header = input.readBytes(headerLength - 4);
header.skip(1); // 跳过 Header Length 字段
final blockFlags = header.readByte();
final nFilters = (blockFlags & 0x3) + 1;
final hasCompressedLength = (blockFlags & 0x40) != 0;
final hasUncompressedLength = (blockFlags & 0x80) != 0;
if (hasCompressedLength) _readMultibyteInteger(header);
if (hasUncompressedLength) _readMultibyteInteger(header);
final filters = <int>[];
var dictionarySize = 0;
for (var i = 0; i < nFilters; i++) {
final id = _readMultibyteInteger(header);
final propLen = _readMultibyteInteger(header);
final props = header.readBytes(propLen).toUint8List();
if (id == 0x21) {
final v = props[0];
if (v > 40) throw ArchiveException('Invalid LZMA dictionary size');
final mantissa = 2 | (v & 0x1);
final exponent = (v >> 1) + 11;
dictionarySize = mantissa << exponent;
filters.add(id);
filters.add(dictionarySize);
} else {
filters.add(id);
filters.add(0);
}
}
_readPadding(header);
header.reset();
final crc = input.readUint32();
if (getCrc32(header.toUint8List()) != crc) {
throw ArchiveException('Invalid block CRC checksum');
}
if (filters.length != 2 && filters.first != 0x21) {
throw ArchiveException('Unsupported filters: $filters');
}
decoder.ensureDictionarySize(dictionarySize);
_readLZMA2(input, sink, onChunk, isCancelled);
_readPadding(input);
// 根据 streamFlags 跳过 Check 校验码
const checkSizes = [0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64];
final checkType = streamFlags & 0xf;
if (checkType < checkSizes.length) {
final skipBytes = checkSizes[checkType];
if (skipBytes > 0) input.skip(skipBytes);
}
}
void _readLZMA2(
InputStreamBase input,
IOSink sink,
void Function(int bytes) onChunk,
bool Function()? isCancelled,
) {
while (true) {
if (isCancelled?.call() == true) return;
final control = input.readByte();
if (control & 0x80 == 0) {
if (control == 0) {
// 结束标记
decoder.reset(resetDictionary: true);
return;
} else if (control == 1) {
// 非压缩数据(重置字典)
decoder.reset(resetDictionary: true);
final length = (input.readByte() << 8 | input.readByte()) + 1;
final bytes = decoder.decodeUncompressed(input.readBytes(length), length);
sink.add(bytes);
onChunk(length);
} else if (control == 2) {
// 非压缩数据(不重置字典)
final length = (input.readByte() << 8 | input.readByte()) + 1;
final bytes = decoder.decodeUncompressed(input.readBytes(length), length);
sink.add(bytes);
onChunk(length);
} else {
throw ArchiveException('Unknown LZMA2 control code $control');
}
} else {
final reset = (control >> 5) & 0x3;
final uncompressedLength = ((control & 0x1f) << 16 |
input.readByte() << 8 |
input.readByte()) +
1;
final compressedLength = (input.readByte() << 8 | input.readByte()) + 1;
int? literalContextBits;
int? literalPositionBits;
int? positionBits;
if (reset >= 2) {
var properties = input.readByte();
positionBits = properties ~/ 45;
properties -= positionBits * 45;
literalPositionBits = properties ~/ 9;
literalContextBits = properties - literalPositionBits * 9;
}
if (reset > 0) {
decoder.reset(
literalContextBits: literalContextBits,
literalPositionBits: literalPositionBits,
positionBits: positionBits,
resetDictionary: reset == 3,
);
}
final chunk = decoder.decode(input.readBytes(compressedLength), uncompressedLength);
sink.add(chunk);
onChunk(uncompressedLength);
}
}
}
int _readStreamIndex(InputStreamBase input) {
final startPosition = input.position;
input.skip(1); // 跳过 index indicator (0x00)
final nRecords = _readMultibyteInteger(input);
for (var i = 0; i < nRecords; i++) {
_readMultibyteInteger(input); // unpaddedLength
_readMultibyteInteger(input); // uncompressedLength
}
_readPadding(input);
final indexLength = input.position - startPosition;
input.rewind(indexLength);
final indexData = input.readBytes(indexLength);
final crc = input.readUint32();
if (getCrc32(indexData.toUint8List()) != crc) {
throw ArchiveException('Invalid stream index CRC checksum');
}
return indexLength + 4;
}
void _readStreamFooter(InputStreamBase input, int indexSize) {
final crc = input.readUint32();
final footer = input.readBytes(6);
final backwardSize = (footer.readUint32() + 1) * 4;
if (backwardSize != indexSize) {
throw ArchiveException('Stream footer has invalid index size');
}
if (footer.readByte() != 0) {
throw ArchiveException('Invalid stream flags');
}
final footerFlags = footer.readByte();
if (footerFlags != streamFlags) {
throw ArchiveException("Stream footer flags don't match header flags");
}
footer.reset();
if (getCrc32(footer.toUint8List()) != crc) {
throw ArchiveException('Invalid stream footer CRC checksum');
}
final magic = input.readBytes(2).toUint8List();
if (magic[0] != 89 || magic[1] != 90) { // 'YZ'
throw ArchiveException('Invalid XZ stream footer signature');
}
}
}
/// 采用固定大小环形缓冲区的高性能低内存 LZMA 解码器
class LowMemoryLzmaDecoder {
final _rc = _LzmaRangeDecoder();
int _positionBits = 2;
int _literalPositionBits = 0;
int _literalContextBits = 3;
final _nonLiteralTables = <_LzmaRangeDecoderTable>[];
late final _LzmaRangeDecoderTable _repeatTable;
late final _LzmaRangeDecoderTable _repeat0Table;
final _longRepeat0Tables = <_LzmaRangeDecoderTable>[];
late final _LzmaRangeDecoderTable _repeat1Table;
late final _LzmaRangeDecoderTable _repeat2Table;
final _literalTables = <_LzmaRangeDecoderTable>[];
final _matchLiteralTables0 = <_LzmaRangeDecoderTable>[];
final _matchLiteralTables1 = <_LzmaRangeDecoderTable>[];
late final _LzmaLengthDecoder _matchLengthDecoder;
late final _LzmaLengthDecoder _repeatLengthDecoder;
late final _LzmaDistanceDecoder _distanceDecoder;
var _distance0 = 0;
var _distance1 = 0;
var _distance2 = 0;
var _distance3 = 0;
var state = _LzmaState.litLit;
Uint8List _dict = Uint8List(0);
int _dictMask = 0;
int _writePos = 0;
LowMemoryLzmaDecoder() {
for (var i = 0; i < _LzmaState.values.length; i++) {
_nonLiteralTables.add(_LzmaRangeDecoderTable(_LzmaState.values.length));
}
_repeatTable = _LzmaRangeDecoderTable(_LzmaState.values.length);
_repeat0Table = _LzmaRangeDecoderTable(_LzmaState.values.length);
for (var i = 0; i < _LzmaState.values.length; i++) {
_longRepeat0Tables.add(_LzmaRangeDecoderTable(_LzmaState.values.length));
}
_repeat1Table = _LzmaRangeDecoderTable(_LzmaState.values.length);
_repeat2Table = _LzmaRangeDecoderTable(_LzmaState.values.length);
var positionCount = 1 << _positionBits;
_matchLengthDecoder = _LzmaLengthDecoder(_rc, positionCount);
_repeatLengthDecoder = _LzmaLengthDecoder(_rc, positionCount);
_distanceDecoder = _LzmaDistanceDecoder(_rc);
reset();
}
/// 确保字典大小为大于等于 [dictSize] 的 2 的整数幂,以便通过位掩码快速寻址
void ensureDictionarySize(int dictSize) {
var capacity = 4096;
while (capacity < dictSize) {
capacity <<= 1;
}
if (_dict.length != capacity) {
_dict = Uint8List(capacity);
_dictMask = capacity - 1;
_writePos = 0;
}
}
void reset({
int? positionBits,
int? literalPositionBits,
int? literalContextBits,
bool resetDictionary = false,
}) {
_positionBits = positionBits ?? _positionBits;
_literalPositionBits = literalPositionBits ?? _literalPositionBits;
_literalContextBits = literalContextBits ?? _literalContextBits;
state = _LzmaState.litLit;
_distance0 = 0;
_distance1 = 0;
_distance2 = 0;
_distance3 = 0;
final maxLiteralStates = 1 << (_literalPositionBits + _literalContextBits);
if (_literalTables.length != maxLiteralStates) {
for (var i = _literalTables.length; i < maxLiteralStates; i++) {
_literalTables.add(_LzmaRangeDecoderTable(256));
_matchLiteralTables0.add(_LzmaRangeDecoderTable(256));
_matchLiteralTables1.add(_LzmaRangeDecoderTable(256));
}
}
for (final table in _nonLiteralTables) {
table.reset();
}
_repeatTable.reset();
_repeat0Table.reset();
for (final table in _longRepeat0Tables) {
table.reset();
}
_repeat1Table.reset();
_repeat2Table.reset();
for (final table in _literalTables) {
table.reset();
}
for (final table in _matchLiteralTables0) {
table.reset();
}
for (final table in _matchLiteralTables1) {
table.reset();
}
final positionCount = 1 << _positionBits;
_matchLengthDecoder.reset(positionCount);
_repeatLengthDecoder.reset(positionCount);
_distanceDecoder.reset();
if (resetDictionary) {
_writePos = 0;
}
}
Uint8List decodeUncompressed(InputStreamBase input, int uncompressedLength) {
final inputBytes = input.readBytes(uncompressedLength).toUint8List();
for (var i = 0; i < uncompressedLength; i++) {
_dict[_writePos & _dictMask] = inputBytes[i];
_writePos++;
}
return inputBytes;
}
Uint8List decode(InputStreamBase input, int uncompressedLength) {
_rc.input = input;
_rc.initialize();
final chunkOut = Uint8List(uncompressedLength);
var chunkOffset = 0;
while (chunkOffset < uncompressedLength) {
final positionMask = (1 << _positionBits) - 1;
final posState = _writePos & positionMask;
if (_rc.readBit(_nonLiteralTables[state.index], posState) == 0) {
_decodeLiteral(chunkOut, chunkOffset);
chunkOffset += 1;
} else if (_rc.readBit(_repeatTable, state.index) == 0) {
final len = _decodeMatch(posState, chunkOut, chunkOffset);
chunkOffset += len;
} else {
final len = _decodeRepeat(posState, chunkOut, chunkOffset);
chunkOffset += len;
}
}
return chunkOut;
}
bool _prevPacketIsLiteral() {
switch (state) {
case _LzmaState.litLit:
case _LzmaState.matchLitLit:
case _LzmaState.repLitLit:
case _LzmaState.shortRepLitLit:
case _LzmaState.matchLit:
case _LzmaState.repLit:
case _LzmaState.shortRepLit:
return true;
case _LzmaState.litMatch:
case _LzmaState.litLongRep:
case _LzmaState.litShortRep:
case _LzmaState.nonLitMatch:
case _LzmaState.nonLitRep:
return false;
}
}
void _decodeLiteral(Uint8List chunkOut, int chunkOffset) {
var prevByte = _writePos > 0 ? _dict[(_writePos - 1) & _dictMask] : 0;
final low = prevByte >> (8 - _literalContextBits);
final positionMask = (1 << _literalPositionBits) - 1;
final high = (_writePos & positionMask) << _literalContextBits;
final hash = low + high;
final table = _literalTables[hash];
int value;
if (_prevPacketIsLiteral()) {
value = _rc.readBittree(table, 8);
} else {
prevByte = _dict[(_writePos - _distance0 - 1) & _dictMask];
value = 0;
var symbolPrefix = 1;
var matched = true;
final matchTable0 = _matchLiteralTables0[hash];
final matchTable1 = _matchLiteralTables1[hash];
for (var i = 0; i < 8; i++) {
int b;
if (matched) {
final matchBit = (prevByte >> 7) & 0x1;
prevByte <<= 1;
b = _rc.readBit(
matchBit == 0 ? matchTable0 : matchTable1, symbolPrefix | value);
matched = b == matchBit;
} else {
b = _rc.readBit(table, symbolPrefix | value);
}
value = (value << 1) | b;
symbolPrefix <<= 1;
}
}
_dict[_writePos & _dictMask] = value;
chunkOut[chunkOffset] = value;
_writePos++;
switch (state) {
case _LzmaState.litLit:
case _LzmaState.matchLitLit:
case _LzmaState.repLitLit:
case _LzmaState.shortRepLitLit:
state = _LzmaState.litLit;
break;
case _LzmaState.matchLit:
state = _LzmaState.matchLitLit;
break;
case _LzmaState.repLit:
state = _LzmaState.repLitLit;
break;
case _LzmaState.shortRepLit:
state = _LzmaState.shortRepLitLit;
break;
case _LzmaState.litMatch:
case _LzmaState.nonLitMatch:
state = _LzmaState.matchLit;
break;
case _LzmaState.litLongRep:
case _LzmaState.nonLitRep:
state = _LzmaState.repLit;
break;
case _LzmaState.litShortRep:
state = _LzmaState.shortRepLit;
break;
}
}
int _decodeMatch(int posState, Uint8List chunkOut, int chunkOffset) {
final length = _matchLengthDecoder.readLength(posState);
final distance = _distanceDecoder.readDistance(length);
_repeatData(distance, length, chunkOut, chunkOffset);
_distance3 = _distance2;
_distance2 = _distance1;
_distance1 = _distance0;
_distance0 = distance;
state =
_prevPacketIsLiteral() ? _LzmaState.litMatch : _LzmaState.nonLitMatch;
return length;
}
int _decodeRepeat(int posState, Uint8List chunkOut, int chunkOffset) {
int distance;
if (_rc.readBit(_repeat0Table, state.index) == 0) {
if (_rc.readBit(_longRepeat0Tables[state.index], posState) == 0) {
_repeatData(_distance0, 1, chunkOut, chunkOffset);
state = _prevPacketIsLiteral()
? _LzmaState.litShortRep
: _LzmaState.nonLitRep;
return 1;
} else {
distance = _distance0;
}
} else if (_rc.readBit(_repeat1Table, state.index) == 0) {
distance = _distance1;
_distance1 = _distance0;
_distance0 = distance;
} else if (_rc.readBit(_repeat2Table, state.index) == 0) {
distance = _distance2;
_distance2 = _distance1;
_distance1 = _distance0;
_distance0 = distance;
} else {
distance = _distance3;
_distance3 = _distance2;
_distance2 = _distance1;
_distance1 = _distance0;
_distance0 = distance;
}
var length = _repeatLengthDecoder.readLength(posState);
_repeatData(distance, length, chunkOut, chunkOffset);
state =
_prevPacketIsLiteral() ? _LzmaState.litLongRep : _LzmaState.nonLitRep;
return length;
}
void _repeatData(int distance, int length, Uint8List chunkOut, int chunkOffset) {
var src = _writePos - distance - 1;
for (var i = 0; i < length; i++) {
if (src < 0 || _writePos < 0) {
break;
}
final b = _dict[src & _dictMask];
_dict[_writePos & _dictMask] = b;
chunkOut[chunkOffset + i] = b;
src++;
_writePos++;
}
}
}
enum _LzmaState {
litLit,
matchLitLit,
repLitLit,
shortRepLitLit,
matchLit,
repLit,
shortRepLit,
litMatch,
litLongRep,
litShortRep,
nonLitMatch,
nonLitRep
}
const _probabilityBitCount = 11;
const _probabilityOne = (1 << _probabilityBitCount);
const _probabilityHalf = _probabilityOne ~/ 2;
class _LzmaRangeDecoderTable {
final Uint16List table;
_LzmaRangeDecoderTable(int length) : table = Uint16List(length) {
reset();
}
void reset() {
table.fillRange(0, table.length, _probabilityHalf);
}
}
class _LzmaRangeDecoder {
late InputStreamBase _input;
var range = 0xffffffff;
var code = 0;
set input(InputStreamBase value) {
_input = value;
}
void reset() {
range = 0xffffffff;
code = 0;
}
void initialize() {
code = 0;
range = 0xffffffff;
_input.skip(1);
for (var i = 0; i < 4; i++) {
code = (code << 8 | _input.readByte());
}
}
int readBit(_LzmaRangeDecoderTable table, int index) {
_load();
final p = table.table[index];
final bound = (range >> _probabilityBitCount) * p;
const moveBits = 5;
if (code < bound) {
range = bound;
final oneMinusP = _probabilityOne - p;
final shifted = oneMinusP >> moveBits;
table.table[index] += shifted;
return 0;
} else {
range -= bound;
code -= bound;
table.table[index] -= p >> moveBits;
return 1;
}
}
int readBittree(_LzmaRangeDecoderTable table, int count) {
var value = 0;
var symbolPrefix = 1;
for (var i = 0; i < count; i++) {
final b = readBit(table, symbolPrefix | value);
value = ((value << 1) | b) & 0xffffffff;
symbolPrefix = (symbolPrefix << 1) & 0xffffffff;
}
return value;
}
int readBittreeReverse(_LzmaRangeDecoderTable table, int count) {
var value = 0;
var symbolPrefix = 1;
for (var i = 0; i < count; i++) {
final b = readBit(table, symbolPrefix | value);
value = (value | b << i) & 0xffffffff;
symbolPrefix = (symbolPrefix << 1) & 0xffffffff;
}
return value;
}
int readDirect(int count) {
var value = 0;
for (var i = 0; i < count; i++) {
_load();
range >>= 1;
code -= range;
value <<= 1;
if (code & 0x80000000 != 0) {
code += range;
} else {
value++;
}
}
return value;
}
void _load() {
const topValue = 1 << 24;
if (range < topValue) {
range <<= 8;
code = (code << 8) | _input.readByte();
}
}
}
class _LzmaLengthDecoder {
final _LzmaRangeDecoder _input;
late final _LzmaRangeDecoderTable formTable;
late final List<_LzmaRangeDecoderTable> shortTables;
late final List<_LzmaRangeDecoderTable> mediumTables;
late final _LzmaRangeDecoderTable longTable;
_LzmaLengthDecoder(this._input, int positionCount) {
formTable = _LzmaRangeDecoderTable(2);
shortTables = <_LzmaRangeDecoderTable>[];
mediumTables = <_LzmaRangeDecoderTable>[];
longTable = _LzmaRangeDecoderTable(256);
reset(positionCount);
}
void reset(int positionCount) {
formTable.reset();
if (positionCount != shortTables.length) {
shortTables.clear();
mediumTables.clear();
for (var i = 0; i < positionCount; i++) {
shortTables.add(_LzmaRangeDecoderTable(8));
mediumTables.add(_LzmaRangeDecoderTable(8));
}
} else {
for (var table in shortTables) {
table.reset();
}
for (var table in mediumTables) {
table.reset();
}
}
longTable.reset();
}
int readLength(int posState) {
if (_input.readBit(formTable, 0) == 0) {
return 2 + _input.readBittree(shortTables[posState], 3);
} else if (_input.readBit(formTable, 1) == 0) {
return 10 + _input.readBittree(mediumTables[posState], 3);
} else {
return 18 + _input.readBittree(longTable, 8);
}
}
}
class _LzmaDistanceDecoder {
final int _slotBitCount = 6;
final int _alignBitCount = 4;
final _LzmaRangeDecoder _input;
late final List<_LzmaRangeDecoderTable> _slotTables;
late final List<_LzmaRangeDecoderTable> _shortTables;
late final _LzmaRangeDecoderTable _longTable;
_LzmaDistanceDecoder(this._input) {
_slotTables = <_LzmaRangeDecoderTable>[];
var slotSize = 1 << _slotBitCount;
for (var i = 0; i < 4; i++) {
_slotTables.add(_LzmaRangeDecoderTable(slotSize));
}
_shortTables = <_LzmaRangeDecoderTable>[];
for (var slot = 4; slot < 14; slot++) {
var bitCount = (slot ~/ 2) - 1;
_shortTables.add(_LzmaRangeDecoderTable(1 << bitCount));
}
var alignSize = 1 << _alignBitCount;
_longTable = _LzmaRangeDecoderTable(alignSize);
}
void reset() {
for (var table in _slotTables) {
table.reset();
}
for (var table in _shortTables) {
table.reset();
}
_longTable.reset();
}
int readDistance(int length) {
var distState = length - 2;
if (distState >= _slotTables.length) {
distState = _slotTables.length - 1;
}
final table = _slotTables[distState];
final slot = _input.readBittree(table, _slotBitCount);
if (slot < 4) return slot;
final prefix = 0x2 | (slot & 0x1);
final bitCount = (slot ~/ 2) - 1;
if (slot < 14) {
final result = (prefix << bitCount) |
_input.readBittreeReverse(_shortTables[slot - 4], bitCount);
return result;
}
final directCount = bitCount - _alignBitCount;
final directBits = _input.readDirect(directCount);
final alignBits = _input.readBittreeReverse(_longTable, _alignBitCount);
final r1 = (prefix << bitCount) & 0xffffffff;
final r2 = (directBits << _alignBitCount) & 0xffffffff;
return r1 | r2 | alignBits;
}
}
+21 -21
View File
@@ -47,7 +47,7 @@ class ProjectTaskDetector {
name: 'CMake: Build & Run',
command: 'cmake -B build && cmake --build build && ./build/$projectName',
source: TaskSource.detected,
description: '配置、编译并尝试启动生成的目标程序',
description: 'Configure, build, and try launching the target executable',
icon: Icons.play_circle_outline,
),
RunTask(
@@ -55,7 +55,7 @@ class ProjectTaskDetector {
name: 'CMake: Build Only',
command: 'cmake -B build && cmake --build build',
source: TaskSource.detected,
description: '仅执行 cmake 生成与构建',
description: 'Only execute cmake generation and build',
icon: Icons.build_outlined,
),
RunTask(
@@ -63,7 +63,7 @@ class ProjectTaskDetector {
name: 'CMake: Clean',
command: 'rm -rf build',
source: TaskSource.detected,
description: '清理构建缓存目录',
description: 'Clean build cache directory',
icon: Icons.cleaning_services_outlined,
),
]);
@@ -74,14 +74,14 @@ class ProjectTaskDetector {
final gradleFile = File(p.join(projectRoot, 'build.gradle'));
final gradleKtsFile = File(p.join(projectRoot, 'build.gradle.kts'));
if (gradlewFile.existsSync() || gradleFile.existsSync() || gradleKtsFile.existsSync()) {
final exec = gradlewFile.existsSync() ? './gradlew' : 'gradle';
final exec = gradlewFile.existsSync() ? 'sh ./gradlew' : 'gradle';
buildTasks.addAll([
RunTask(
id: 'detected_gradle_run',
name: 'Gradle: Run',
command: '$exec run',
source: TaskSource.detected,
description: '执行应用程序主入口',
description: 'Execute application main entrypoint',
icon: Icons.play_circle_outline,
),
RunTask(
@@ -89,7 +89,7 @@ class ProjectTaskDetector {
name: 'Gradle: Assemble Debug',
command: '$exec assembleDebug',
source: TaskSource.detected,
description: '构建调试输出包',
description: 'Build debug output package',
icon: Icons.build_outlined,
),
RunTask(
@@ -97,7 +97,7 @@ class ProjectTaskDetector {
name: 'Gradle: Build',
command: '$exec build',
source: TaskSource.detected,
description: '执行完整构建与测试',
description: 'Execute full build and tests',
icon: Icons.done_all_outlined,
),
]);
@@ -112,7 +112,7 @@ class ProjectTaskDetector {
name: 'Make: Default',
command: 'make',
source: TaskSource.detected,
description: '执行默认 Makefile 构建目标',
description: 'Execute default Makefile build target',
icon: Icons.build_circle_outlined,
),
);
@@ -127,7 +127,7 @@ class ProjectTaskDetector {
name: 'NPM: Start',
command: 'npm start',
source: TaskSource.detected,
description: '启动 Node 服务或前端开发环境',
description: 'Start Node service or frontend development environment',
icon: Icons.rocket_launch_outlined,
),
const RunTask(
@@ -135,7 +135,7 @@ class ProjectTaskDetector {
name: 'NPM: Test',
command: 'npm test',
source: TaskSource.detected,
description: '执行 npm test 测试套件',
description: 'Execute npm test suite',
icon: Icons.checklist_outlined,
),
]);
@@ -150,7 +150,7 @@ class ProjectTaskDetector {
name: 'Cargo: Run',
command: 'cargo run',
source: TaskSource.detected,
description: '编译并运行 Rust 项目',
description: 'Compile and run Rust project',
icon: Icons.play_circle_outline,
),
const RunTask(
@@ -158,7 +158,7 @@ class ProjectTaskDetector {
name: 'Cargo: Build',
command: 'cargo build',
source: TaskSource.detected,
description: '仅编译 Rust 项目',
description: 'Compile Rust project only',
icon: Icons.build_outlined,
),
]);
@@ -173,7 +173,7 @@ class ProjectTaskDetector {
name: 'Dart: Run',
command: 'dart run',
source: TaskSource.detected,
description: '启动 Dart 应用',
description: 'Launch Dart application',
icon: Icons.play_circle_outline,
),
);
@@ -203,7 +203,7 @@ class ProjectTaskDetector {
name: 'Python: $fileName',
command: 'python3 "$relPath"',
source: TaskSource.detected,
description: '运行当前 Python 脚本',
description: 'Run current Python script',
icon: Icons.code,
);
case '.c':
@@ -212,7 +212,7 @@ class ProjectTaskDetector {
name: 'GCC: $fileName',
command: 'gcc "$relPath" -o /tmp/a.out && /tmp/a.out',
source: TaskSource.detected,
description: '编译并执行当前 C 源文件',
description: 'Compile and execute current C source file',
icon: Icons.terminal,
);
case '.cpp':
@@ -223,7 +223,7 @@ class ProjectTaskDetector {
name: 'G++: $fileName',
command: 'g++ "$relPath" -o /tmp/a.out && /tmp/a.out',
source: TaskSource.detected,
description: '编译并执行当前 C++ 源文件',
description: 'Compile and execute current C++ source file',
icon: Icons.terminal,
);
case '.sh':
@@ -233,7 +233,7 @@ class ProjectTaskDetector {
name: 'Shell: $fileName',
command: 'sh "$relPath"',
source: TaskSource.detected,
description: '运行当前 Shell 脚本',
description: 'Run current Shell script',
icon: Icons.terminal,
);
case '.dart':
@@ -242,7 +242,7 @@ class ProjectTaskDetector {
name: 'Dart: $fileName',
command: 'dart run "$relPath"',
source: TaskSource.detected,
description: '运行当前 Dart 文件',
description: 'Run current Dart file',
icon: Icons.code,
);
case '.go':
@@ -251,7 +251,7 @@ class ProjectTaskDetector {
name: 'Go: $fileName',
command: 'go run "$relPath"',
source: TaskSource.detected,
description: '运行当前 Go 源文件',
description: 'Run current Go source file',
icon: Icons.code,
);
case '.rs':
@@ -260,7 +260,7 @@ class ProjectTaskDetector {
name: 'Rust: $fileName',
command: 'rustc "$relPath" -o /tmp/a.out && /tmp/a.out',
source: TaskSource.detected,
description: '编译并执行当前 Rust 源文件',
description: 'Compile and execute current Rust source file',
icon: Icons.code,
);
case '.js':
@@ -269,7 +269,7 @@ class ProjectTaskDetector {
name: 'Node: $fileName',
command: 'node "$relPath"',
source: TaskSource.detected,
description: '运行当前 JS 脚本',
description: 'Run current JavaScript script',
icon: Icons.javascript,
);
default:
+13 -10
View File
@@ -28,22 +28,25 @@ class RunTaskStorageService {
}
final dynamic decoded = jsonDecode(content);
if (decoded is Map<String, dynamic>) {
final lastId = decoded['lastRunTaskId'] as String?;
if (decoded is Map) {
final lastId = decoded['lastRunTaskId']?.toString();
final tasksRaw = decoded['tasks'];
List<RunTask> list = [];
if (tasksRaw is List) {
list = tasksRaw
.whereType<Map<String, dynamic>>()
.map((item) => RunTask.fromJson(item))
.toList();
for (final item in tasksRaw) {
if (item is Map) {
list.add(RunTask.fromJson(Map<String, dynamic>.from(item)));
}
}
}
return (tasks: list, lastRunTaskId: lastId);
} else if (decoded is List) {
final list = decoded
.whereType<Map<String, dynamic>>()
.map((item) => RunTask.fromJson(item))
.toList();
List<RunTask> list = [];
for (final item in decoded) {
if (item is Map) {
list.add(RunTask.fromJson(Map<String, dynamic>.from(item)));
}
}
return (tasks: list, lastRunTaskId: null);
}
return (tasks: <RunTask>[], lastRunTaskId: null);
+379
View File
@@ -0,0 +1,379 @@
import 'dart:io';
import 'package:path/path.dart' as p;
import 'distro_manager.dart';
/// 单个工具链依赖规格定义
class ToolchainRequirement {
/// 用于检测是否已安装的可执行文件名(传入 command -v)
final String checkBinary;
/// 用户可见的工具名称/描述
final String displayName;
/// 针对不同发行版家族的自动安装指令
final Map<DistroFamily, String> installCommands;
const ToolchainRequirement({
required this.checkBinary,
required this.displayName,
required this.installCommands,
});
/// 获取指定发行版家族下的安装命令
String? getInstallCommand(DistroFamily family) => installCommands[family];
}
/// 预编译软件源与工具链检测/安装适配服务
class ToolchainService {
/// 已注册的常用编译器与开发工具链元数据
static const Map<String, ToolchainRequirement> supportedTools = {
'make': ToolchainRequirement(
checkBinary: 'make',
displayName: 'make 编译构建工具',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache make build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y make gcc gcc-c++',
},
),
'cmake': ToolchainRequirement(
checkBinary: 'cmake',
displayName: 'cmake 构建套件',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache cmake make build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm cmake base-devel',
DistroFamily.fedora: 'dnf install -y cmake make gcc gcc-c++',
},
),
'gcc': ToolchainRequirement(
checkBinary: 'gcc',
displayName: 'GCC C 语言编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache gcc musl-dev build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y gcc gcc-c++',
},
),
'g++': ToolchainRequirement(
checkBinary: 'g++',
displayName: 'G++ C++ 编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache g++ musl-dev build-base',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
DistroFamily.fedora: 'dnf install -y gcc-c++',
},
),
'python3': ToolchainRequirement(
checkBinary: 'python3',
displayName: 'Python 3 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
},
),
'python': ToolchainRequirement(
checkBinary: 'python3',
displayName: 'Python 3 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
},
),
'npm': ToolchainRequirement(
checkBinary: 'npm',
displayName: 'Node.js 与 NPM 环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
DistroFamily.fedora: 'dnf install -y nodejs npm',
},
),
'node': ToolchainRequirement(
checkBinary: 'node',
displayName: 'Node.js 运行环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
DistroFamily.fedora: 'dnf install -y nodejs npm',
},
),
'cargo': ToolchainRequirement(
checkBinary: 'cargo',
displayName: 'Rust 与 Cargo 工具链',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
DistroFamily.fedora: 'dnf install -y cargo rust',
},
),
'rustc': ToolchainRequirement(
checkBinary: 'rustc',
displayName: 'Rust 编译器',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
DistroFamily.fedora: 'dnf install -y cargo rust',
},
),
'go': ToolchainRequirement(
checkBinary: 'go',
displayName: 'Go 语言环境',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache go',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
DistroFamily.arch: 'pacman -Sy --noconfirm go',
DistroFamily.fedora: 'dnf install -y golang',
},
),
'gradle': ToolchainRequirement(
checkBinary: 'java',
displayName: 'Java / Gradle 运行时',
installCommands: {
DistroFamily.alpine: 'apk update && apk add --no-cache openjdk17-jre-headless',
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
DistroFamily.arch: 'pacman -Sy --noconfirm jdk-openjdk',
DistroFamily.fedora: 'dnf install -y java-latest-openjdk-devel',
},
),
};
/// 从命令行文本中提取所有潜在调用的工具关键字
static List<ToolchainRequirement> detectRequiredTools(String command) {
if (command.trim().isEmpty) return const [];
final List<ToolchainRequirement> detected = [];
final seen = <String>{};
// 按语句分隔符拆解:&&, ||, ;, |, 换行
final statements = command.split(RegExp(r'&&|\|\||;|\||\n'));
for (var stmt in statements) {
stmt = stmt.trim();
if (stmt.isEmpty) continue;
// 提取语句开头的可执行文件名或路径(支持前置 sudo、sh、bash,支持 ./gradlew、/usr/bin/make 等)
final match = RegExp(r'^(?:sudo\s+)?(?:(?:sh|bash)\s+)?([a-zA-Z0-9_\.\-\+\/\\]+)').firstMatch(stmt);
if (match != null) {
var rawBin = match.group(1)!;
// 归一化提取二进制文件名
var binName = rawBin.split(RegExp(r'[/\\]')).last;
if (binName == 'gradlew' || binName == 'gradle') {
binName = 'gradle';
}
if (supportedTools.containsKey(binName)) {
final req = supportedTools[binName]!;
if (!seen.contains(req.checkBinary)) {
seen.add(req.checkBinary);
detected.add(req);
}
}
}
}
return detected;
}
/// 检查目标发行版根文件系统中是否已经物理安装了指定工具
static bool isToolInstalledInRootfs(Directory rootDir, String checkBinary) {
// 候选二进制名称
final binariesToCheck = <String>[checkBinary];
if (checkBinary == 'python3') binariesToCheck.add('python');
if (checkBinary == 'node') binariesToCheck.add('nodejs');
if (checkBinary == 'npm') binariesToCheck.add('npm');
final candidateSubDirs = [
['usr', 'bin'],
['bin'],
['usr', 'local', 'bin'],
['sbin'],
['usr', 'sbin'],
['root', '.cargo', 'bin'],
['root', '.local', 'bin'],
['root', 'go', 'bin'],
['usr', 'lib', 'jvm', 'default-java', 'bin'],
];
for (final bin in binariesToCheck) {
for (final subDir in candidateSubDirs) {
final fullPath = p.joinAll([rootDir.path, ...subDir, bin]);
try {
final type = FileSystemEntity.typeSync(fullPath, followLinks: false);
if (type != FileSystemEntityType.notFound) {
return true;
}
} catch (_) {}
}
}
if (checkBinary == 'java') {
final jvmDir = Directory(p.join(rootDir.path, 'usr', 'lib', 'jvm'));
if (jvmDir.existsSync()) {
try {
for (final entry in jvmDir.listSync()) {
if (entry is Directory) {
final javaBin = File(p.join(entry.path, 'bin', 'java'));
if (javaBin.existsSync()) return true;
}
}
} catch (_) {}
}
}
return false;
}
/// 针对不同系统与命令生成自适应的预安装与执行组合脚本
///
/// - 只有识别出明确发行版家族(Alpine/Ubuntu/Debian/Arch/Fedora)的系统,才会生成前置检测与安装包装;
/// - 针对未识别的未知系统([DistroFamily.unknown])或宿主 Shell,直接原样返回指令,不作任何干预;
/// - 若传入 [rootDir],将优先在宿主文件系统快速检测工具是否已物理存在,已存在则直接返回原命令;
/// - 若命令为多行脚本(包含换行符),将自动转换为 Unix LF 换行并保存至容器 `/root/.ce_task.sh` 执行,
/// 彻底避免交互式终端在提示符处逐行错位回显;
/// - 若工具缺失,将把工具安装逻辑一并注入引导脚本中,保证执行的平滑与终端的清爽。
static String resolveCommand(
String rawCommand,
DistroFamily family, {
Directory? rootDir,
}) {
if (rawCommand.trim().isEmpty) {
return rawCommand;
}
// 1. 规范化统一换行符为 Unix LF,防止 Windows CRLF 导致 /bin/sh: $'\r': command not found
final normalizedCommand = rawCommand.replaceAll('\r\n', '\n').replaceAll('\r', '\n').trim();
final isMultiLine = normalizedCommand.contains('\n');
// 2. 识别所需工具链
final tools = detectRequiredTools(normalizedCommand);
// 3. 计算实际物理缺失的工具
List<ToolchainRequirement> missingTools = [];
if (family != DistroFamily.unknown && tools.isNotEmpty) {
if (rootDir != null && rootDir.existsSync()) {
missingTools = tools
.where((tool) => !isToolInstalledInRootfs(rootDir, tool.checkBinary))
.toList();
} else {
missingTools = tools;
}
}
// 4. 多行脚本(Multiline Script)模式:封装为 /root/.ce_task.sh 运行
if (isMultiLine && rootDir != null && rootDir.existsSync()) {
try {
final rootHomeDir = Directory(p.join(rootDir.path, 'root'));
if (!rootHomeDir.existsSync()) {
rootHomeDir.createSync(recursive: true);
}
final taskFile = File(p.join(rootHomeDir.path, '.ce_task.sh'));
final scriptBuffer = StringBuffer();
scriptBuffer.writeln('#!/bin/sh');
scriptBuffer.writeln('set -e');
// 若存在缺失的编译工具链依赖,前置注入自动安装
for (final tool in missingTools) {
final installCmd = tool.getInstallCommand(family);
if (installCmd == null || installCmd.isEmpty) continue;
scriptBuffer.writeln("printf '\\033[1;33m[CodeEditor] 检测到未安装 %s,正在自动配置编译环境...\\033[0m\\n' '${tool.displayName}'");
scriptBuffer.writeln(installCmd);
scriptBuffer.writeln("printf '\\033[1;32m[CodeEditor] %s 安装就绪,继续执行任务...\\033[0m\\n' '${tool.displayName}'");
}
// 注入用户编写的多行脚本内容
scriptBuffer.writeln(normalizedCommand);
taskFile.writeAsStringSync(scriptBuffer.toString());
return 'sh /root/.ce_task.sh';
} catch (_) {
// 异常降级
}
}
// 5. 单行指令且未知系统:原样返回
if (family == DistroFamily.unknown || tools.isEmpty) {
return rawCommand;
}
// 6. 单行指令且所有工具已物理就绪:直接返回原命令,零污染无感直达
if (rootDir != null && rootDir.existsSync() && missingTools.isEmpty) {
return rawCommand;
}
// 7. 单行指令且存在缺失工具:构建轻量 /root/.ce_setup.sh
if (rootDir != null && rootDir.existsSync() && missingTools.isNotEmpty) {
try {
final rootHomeDir = Directory(p.join(rootDir.path, 'root'));
if (!rootHomeDir.existsSync()) {
rootHomeDir.createSync(recursive: true);
}
final setupFile = File(p.join(rootHomeDir.path, '.ce_setup.sh'));
final scriptBuffer = StringBuffer();
scriptBuffer.writeln('#!/bin/sh');
scriptBuffer.writeln('set -e');
for (final tool in missingTools) {
final installCmd = tool.getInstallCommand(family);
if (installCmd == null || installCmd.isEmpty) continue;
scriptBuffer.writeln("printf '\\033[1;33m[CodeEditor] 检测到未安装 %s,正在自动配置编译环境...\\033[0m\\n' '${tool.displayName}'");
scriptBuffer.writeln(installCmd);
scriptBuffer.writeln("printf '\\033[1;32m[CodeEditor] %s 安装就绪,继续执行任务...\\033[0m\\n' '${tool.displayName}'");
}
setupFile.writeAsStringSync(scriptBuffer.toString());
return 'sh /root/.ce_setup.sh && ($rawCommand)';
} catch (_) {
// 异常降级
}
}
// 5. 降级方案(未传 rootDir 或写入失败时的内联防护)
final checks = <String>[];
for (final tool in missingTools) {
final installCmd = tool.getInstallCommand(family);
if (installCmd == null || installCmd.isEmpty) {
continue;
}
final checkScript =
'if ! command -v ${tool.checkBinary} >/dev/null 2>&1; then '
"printf '\\033[1;33m[CodeEditor] 检测到未安装 %s,正在自动配置编译环境...\\033[0m\\n' '${tool.displayName}'; "
'$installCmd; '
'if [ \$? -eq 0 ]; then '
"printf '\\033[1;32m[CodeEditor] %s 安装就绪,继续执行任务...\\033[0m\\n' '${tool.displayName}'; "
'else '
"printf '\\033[1;31m[CodeEditor] %s 安装失败,请检查网络或软件源配置。\\033[0m\\n' '${tool.displayName}'; "
'exit 1; '
'fi; '
'fi';
checks.add(checkScript);
}
if (checks.isEmpty) {
return rawCommand;
}
final preamble = checks.join(' && ');
return '$preamble && ($rawCommand)';
}
}
+59
View File
@@ -204,6 +204,65 @@ class DialogUtils {
);
}
/// 同步居中转圈弹窗(任务执行过程中锁定,任务结束后自动 pop 关闭)
static Future<T> showSyncLoadingDialog<T>(
BuildContext context, {
required String message,
required Future<T> Function() task,
}) async {
final theme = Theme.of(context);
bool dialogPopped = false;
// 弹出不可取消的居中转圈模态框
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (dialogCtx) {
return PopScope(
canPop: false,
child: AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
side: BorderSide(
color: theme.colorScheme.outlineVariant,
width: 1.0,
),
),
content: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 20),
Text(
message,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14.0,
color: theme.colorScheme.onSurface,
),
),
],
),
),
),
);
},
).then((_) {
dialogPopped = true;
});
try {
final result = await task();
return result;
} finally {
if (!dialogPopped && context.mounted) {
Navigator.of(context, rootNavigator: true).pop();
}
}
}
// ==========================================
// 3. 确认弹窗 (普通确认 vs 特殊/高危确认)
// ==========================================
+433
View File
@@ -0,0 +1,433 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/services/distro_download_manager.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
/// 独立的系统管理与发行版包选择视图页面
///
/// 功能:
/// 1. AppBar 包含返回键与标题“系统管理”(遵循 l10n 国际化)。
/// 2. 列举当前架构支持的系统安装包(左侧图标、两行名称与版本,无高亮选框,无“内置”字样)。
/// 3. 安装包项分为两种状态:
/// - 已就绪 (zip 存在):
/// * 不显示“已安装”文本,不显示“安装”按键;
/// * Ubuntu 和 Alpine 为内置包,受保护右侧不显示删除按键;
/// * 在线下载的系统包右侧显示红色删除按钮(二次确认后居中同步转圈删除离线包);
/// * 用户直接点击该项卡片,即代表选中该安装包,返回上一页进行解压创建系统。
/// - 未下载 / 下载中:
/// * 未下载显示“下载”按键;
/// * 下载中显示百分比进度条与取消按键(取消后清空临时文件)。
class DistroManagementView extends StatefulWidget {
const DistroManagementView({super.key});
@override
State<DistroManagementView> createState() => _DistroManagementViewState();
}
class _DistroManagementViewState extends State<DistroManagementView> {
final DistroDownloadManager _downloadManager = DistroDownloadManager();
final Set<String> _downloadedPackageIds = {};
@override
void initState() {
super.initState();
_downloadManager.addListener(_onDownloadProgressChanged);
_checkDownloadedPackages();
}
@override
void dispose() {
_downloadManager.removeListener(_onDownloadProgressChanged);
super.dispose();
}
void _onDownloadProgressChanged() {
if (mounted) {
for (final entry in _downloadManager.allProgress.entries) {
if (entry.value.state == DistroDownloadState.completed) {
_downloadedPackageIds.add(entry.key);
}
}
setState(() {});
}
}
Future<void> _checkDownloadedPackages() async {
final distros = DistroRepository.currentArchDistros;
final Set<String> downloaded = {};
for (final d in distros) {
if (!d.isBuiltin && d.currentPackageSource != null) {
if (await _downloadManager.isPackageDownloaded(d.id, d.currentPackageSource)) {
downloaded.add(d.id);
}
}
}
for (final entry in _downloadManager.allProgress.entries) {
if (entry.value.state == DistroDownloadState.completed) {
downloaded.add(entry.key);
}
}
if (mounted) {
setState(() {
_downloadedPackageIds.clear();
_downloadedPackageIds.addAll(downloaded);
});
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
// 当前架构支持的发行版清单
final distros = DistroRepository.currentArchDistros;
return Scaffold(
appBar: AppBar(
title: Text(
l10n.distroManagementTitle,
style: const TextStyle(fontWeight: FontWeight.bold),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
),
body: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
itemCount: distros.length,
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final item = distros[index];
final downloadProgress = _downloadManager.getProgress(item.id);
final isDownloaded = _downloadedPackageIds.contains(item.id) ||
downloadProgress?.state == DistroDownloadState.completed;
final isReady = item.isBuiltin || isDownloaded;
final isDownloading = downloadProgress?.state == DistroDownloadState.downloading;
return _buildDistroCard(
context: context,
theme: theme,
l10n: l10n,
item: item,
isReady: isReady,
isDownloading: isDownloading,
downloadProgress: downloadProgress,
);
},
),
);
}
Widget _buildDistroCard({
required BuildContext context,
required ThemeData theme,
required AppLocalizations l10n,
required DistroManifestItem item,
required bool isReady,
required bool isDownloading,
required DistroDownloadProgress? downloadProgress,
}) {
return Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
side: BorderSide(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
width: 1.0,
),
),
color: theme.colorScheme.surface,
child: InkWell(
borderRadius: BorderRadius.circular(12.0),
onTap: isReady
? () {
// 点击已就绪的安装包 item:代表选择该 zip,返回上一页解压创建系统
Navigator.of(context).pop(item);
}
: null,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
// 1. 系统左侧品牌图标
Container(
width: 44,
height: 44,
padding: const EdgeInsets.all(6.0),
decoration: BoxDecoration(
color: item.brandColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: item.brandColor.withValues(alpha: 0.3),
width: 1.0,
),
),
child: item.assetIconPath != null
? Image.asset(
item.assetIconPath!,
fit: BoxFit.contain,
errorBuilder: (_, _, _) => Icon(
item.iconData,
color: item.brandColor,
size: 26,
),
)
: Icon(
item.iconData,
color: item.brandColor,
size: 26,
),
),
const SizedBox(width: 14),
// 2. 中间两行文本 (系统名与推荐标签 + 版本)
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(
item.name,
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
if (item.isRecommended) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 2.0),
decoration: BoxDecoration(
color: Colors.amber.shade700.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(6.0),
border: Border.all(
color: Colors.amber.shade800.withValues(alpha: 0.4),
width: 0.8,
),
),
child: Text(
l10n.recommendedTag,
style: TextStyle(
fontSize: 10.5,
fontWeight: FontWeight.bold,
color: Colors.amber.shade800,
),
),
),
],
],
),
const SizedBox(height: 3),
Text(
item.version,
style: TextStyle(
fontSize: 12.0,
color: theme.colorScheme.onSurfaceVariant,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
// 3. 右侧状态与操作按钮
const SizedBox(width: 10),
_buildTrailingAction(
context: context,
theme: theme,
l10n: l10n,
item: item,
isReady: isReady,
isDownloading: isDownloading,
downloadProgress: downloadProgress,
),
],
),
// 若处于下载中,展示下载进度条与百分比
if (isDownloading && downloadProgress != null) ...[
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(4.0),
child: LinearProgressIndicator(
value: downloadProgress.totalBytes > 0
? downloadProgress.progress
: null,
minHeight: 5,
),
),
),
const SizedBox(width: 10),
Text(
'${(downloadProgress.progress * 100).toStringAsFixed(0)}%',
style: TextStyle(
fontSize: 11.5,
fontWeight: FontWeight.w600,
color: theme.colorScheme.primary,
),
),
],
),
],
],
),
),
),
);
}
Widget _buildTrailingAction({
required BuildContext context,
required ThemeData theme,
required AppLocalizations l10n,
required DistroManifestItem item,
required bool isReady,
required bool isDownloading,
required DistroDownloadProgress? downloadProgress,
}) {
if (isReady) {
// 对于已就绪 (已安装) 的 item (zip 文件):
// 不显示“已安装”文本,不显示“安装”按键。
// 对于内置 ubuntu 和 alpine,受保护无按键 (SizedBox.shrink);
// 其他在线下载完成的包,右侧直接显示红色删除按钮
if (item.isBuiltin) {
return const SizedBox.shrink();
}
return IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.redAccent, size: 22),
tooltip: l10n.deletePackageTooltip,
onPressed: () => _handleDeleteDownloadedPackage(item),
);
}
if (isDownloading) {
// 下载中状态:显示取消下载按钮
return IconButton(
icon: const Icon(Icons.cancel_outlined, color: Colors.grey, size: 22),
tooltip: l10n.cancelDownloadAction,
onPressed: () => _handleCancelDownload(item),
);
}
// 未就绪/未下载状态:显示下载按钮
return FilledButton.tonalIcon(
icon: const Icon(Icons.download_outlined, size: 18),
label: Text(l10n.downloadAction),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
textStyle: const TextStyle(fontSize: 13.0),
),
onPressed: () => _handleStartDownload(item),
);
}
/// 启动在线下载
Future<void> _handleStartDownload(DistroManifestItem item) async {
final url = item.currentPackageSource;
final l10n = AppLocalizations.of(context)!;
final settings = context.read<SettingsProvider>();
final mirror = settings.downloadMirror;
if (url == null || url.isEmpty) return;
// 前置资源检测:若已下载完备,立即更新状态并拒绝重复下载
if (await _downloadManager.isPackageDownloaded(item.id, url)) {
if (mounted) {
setState(() {
_downloadedPackageIds.add(item.id);
});
}
return;
}
final targetFile = await _downloadManager.startDownload(
distroId: item.id,
downloadUrl: url,
mirror: mirror,
manifestItem: item,
);
if (targetFile != null && mounted) {
setState(() {
_downloadedPackageIds.add(item.id);
});
} else if (mounted) {
final progress = _downloadManager.getProgress(item.id);
if (progress?.state == DistroDownloadState.failed) {
DialogUtils.showErrorToast(
context,
l10n.downloadFailed(progress?.errorMessage ?? ''),
);
}
}
}
/// 取消下载确认弹窗
Future<void> _handleCancelDownload(DistroManifestItem item) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await DialogUtils.showConfirmDialog(
context,
title: l10n.cancelDownloadConfirmTitle,
message: l10n.cancelDownloadConfirmMessage,
);
if (confirmed && mounted) {
await _downloadManager.cancelDownload(item.id);
}
}
/// 删除已下载的系统安装包(弹确认 Dialog -> 居中转圈同步 Dialog -> 完成)
Future<void> _handleDeleteDownloadedPackage(DistroManifestItem item) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
context,
title: l10n.deletePackageConfirmTitle,
message: l10n.deletePackageConfirmMessage(item.name),
confirmText: l10n.permanentDelete,
);
if (!confirmed || !mounted) return;
// 弹出居中转圈的同步等待弹窗,直至删除完毕
await DialogUtils.showSyncLoadingDialog<void>(
context,
message: l10n.deletingPackageProgress,
task: () async {
try {
await _downloadManager.deletePackage(item.id, item.currentPackageSource);
if (mounted) {
setState(() {
_downloadedPackageIds.remove(item.id);
});
}
} catch (e) {
if (mounted) {
DialogUtils.showErrorToast(context, e.toString());
}
}
},
);
if (mounted) {
DialogUtils.showToast(context, l10n.deletePackageSuccess(item.name));
}
}
}
+136 -24
View File
@@ -1,9 +1,13 @@
import 'dart:async';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/run_task.dart';
import 'package:code_editor/providers/distro_provider.dart';
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/distro_manager.dart';
import 'package:code_editor/services/toolchain_service.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/views/settings_view.dart';
import 'package:code_editor/views/terminal_view.dart';
@@ -12,8 +16,10 @@ import 'package:code_editor/widgets/code_editor_drawer.dart';
import 'package:code_editor/widgets/code_editor_tab_bar.dart';
import 'package:code_editor/widgets/code_editor_widget.dart';
import 'package:code_editor/views/run_task_edit_view.dart';
import 'package:code_editor/widgets/distro_selector_dialog.dart';
import 'package:code_editor/widgets/run_tasks_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
class MainView extends StatefulWidget {
@@ -87,9 +93,63 @@ class _MainViewState extends State<MainView> {
}
}
/// 执行某个具体的运行任务(复用/创建当前工程工作目录的终端并执行指令)
void _executeRunTask(BuildContext context, RunTask task) {
static DistroProvider? _getDistroProvider(BuildContext context, {bool listen = false}) {
try {
return listen ? Provider.of<DistroProvider>(context, listen: listen) : Provider.of<DistroProvider>(context, listen: false);
} catch (_) {
return null;
}
}
/// 提示用户缺失 Linux 执行环境并引导前往系统管理进行配置
void _showMissingDistroDialog(BuildContext context, String? targetDistro) {
final l10n = AppLocalizations.of(context)!;
showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
title: Row(
children: [
const Icon(Icons.warning_amber_rounded, color: Colors.orange, size: 24),
const SizedBox(width: 8),
Expanded(
child: Text(
l10n.missingDistroTitle,
overflow: TextOverflow.ellipsis,
),
),
],
),
content: Text(
targetDistro == null
? l10n.noDistroAvailableContent
: l10n.distroNotInstalledContent(targetDistro),
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(),
child: Text(l10n.cancel),
),
ElevatedButton.icon(
onPressed: () {
Navigator.of(ctx).pop();
DistroSelectorDialog.show(context);
},
icon: const Icon(Icons.dns_outlined, size: 18),
label: Text(l10n.systemManagement),
),
],
),
);
}
/// 执行某个具体的运行任务(前置校验环境、识别工具链并推入终端 PTY 执行)
Future<void> _executeRunTask(BuildContext context, RunTask task) async {
final projectProvider = _getProjectProvider(context);
final terminalProvider = _getTerminalProvider(context);
final runProvider = _getRunProvider(context);
final distroProvider = _getDistroProvider(context);
final l10n = AppLocalizations.of(context)!;
final rootPath = projectProvider.rootPath;
if (rootPath == null || rootPath.isEmpty) {
@@ -97,34 +157,66 @@ class _MainViewState extends State<MainView> {
return;
}
final terminalProvider = _getTerminalProvider(context);
final runProvider = _getRunProvider(context);
final distroManager = DistroManager();
var targetDistro = distroProvider?.selectedSystem;
// 1. 查找或创建绑定了该工程工作路径的终端会话(保持系统默认会话名称)
final session = terminalProvider?.getOrCreateSessionForProject(
projectRoot: rootPath,
distroId: 'alpine',
// 1. 运行前环境可用性前置拦截校验与状态自动校准
// 如果尚未选定系统,或者已选系统校验未通过,主动重新扫描物理系统列表进行校准
if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) {
if (distroProvider != null) {
await distroProvider.refreshSystems();
targetDistro = distroProvider.selectedSystem;
}
// 如果 Provider 仍未选定,兜底从物理已安装列表中选取并同步
if (targetDistro == null || !(await distroManager.isSystemInstalled(targetDistro))) {
final physicalSystems = await distroManager.listInstalledSystems();
if (physicalSystems.isNotEmpty) {
targetDistro = physicalSystems.first;
await distroProvider?.selectSystem(targetDistro);
}
}
}
final hasDistro = targetDistro != null && await distroManager.isSystemInstalled(targetDistro);
if (!hasDistro) {
if (!context.mounted) return;
_showMissingDistroDialog(context, targetDistro);
return;
}
// 2. 识别目标系统发行版家族并自适应合成工具链前置检测/安装命令
final family = await distroManager.detectDistroFamily(targetDistro);
final rootDir = await distroManager.getSystemRootDir(targetDistro);
final effectiveCommand = ToolchainService.resolveCommand(
task.command,
family,
rootDir: rootDir,
);
// 2. 记录最近执行的任务
// 3. 查找或创建绑定了该工程工作路径与目标系统的终端会话
final session = terminalProvider?.getOrCreateSessionForProject(
projectRoot: rootPath,
distroId: targetDistro,
);
// 4. 记录最近执行的任务
runProvider?.setLastRunTask(task);
// 3. 跳转至终端视图
// 5. 跳转至终端视图
if (!context.mounted) return;
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => const TerminalView(),
),
);
// 4. 等待界面跳转后向终端发送指令
Future.delayed(const Duration(milliseconds: 300), () {
// 6. 执行任务命令(推入底层 PTY 的 stdin 并等待进程就绪)
if (session != null) {
if (task.clearBeforeRun) {
session.write('clear\r\n');
session.clear();
}
session.write('${task.command}\r\n');
unawaited(session.executeCommand(effectiveCommand));
}
});
}
/// 点击运行按钮 (Play):有历史任务或单文件即直接执行,否则弹出任务列表
@@ -140,13 +232,13 @@ class _MainViewState extends State<MainView> {
final runProvider = _getRunProvider(context);
if (runProvider == null) return;
// 优先: 最近运行的任务(若已持久化并存在)
if (runProvider.lastRunTask != null) {
// 优先: 最近运行的任务(若已持久化并存在且确实属于当前打开的工程)
if (runProvider.currentProjectRoot == rootPath && runProvider.lastRunTask != null) {
_executeRunTask(context, runProvider.lastRunTask!);
return;
}
// 若没有上一次运行的任务,直接打开运行任务列表
// 若当前项目尚未初始化完成或没有上一次运行的任务,直接打开运行任务列表
_handleOpenRunTasksDialog(context);
}
@@ -162,11 +254,18 @@ class _MainViewState extends State<MainView> {
return;
}
// 如果 runProvider 尚未绑定当前项目,立即触发同步
if (runProvider.currentProjectRoot != rootPath) {
final tabProvider = _getTabProvider(context);
runProvider.onProjectOpened(rootPath, activeFilePath: tabProvider.currentFilePath);
}
final isCurrentProject = runProvider.currentProjectRoot == rootPath;
RunTasksDialog.show(
context: context,
customTasks: runProvider.customTasks,
detectedTasks: runProvider.detectedTasks,
lastRunTaskId: runProvider.lastRunTaskId ?? runProvider.lastRunTask?.id,
customTasks: isCurrentProject ? runProvider.customTasks : const [],
detectedTasks: isCurrentProject ? runProvider.detectedTasks : const [],
lastRunTaskId: isCurrentProject ? (runProvider.lastRunTaskId ?? runProvider.lastRunTask?.id) : null,
onTaskSelected: (task) => _executeRunTask(context, task),
onEditCustomTasks: () => _handleOpenEditRunTasks(context),
);
@@ -236,22 +335,35 @@ class _MainViewState extends State<MainView> {
final isModified = tabProvider.isModified;
// 当检测到切换了项目根目录时,自动触发初始化并进行一次探测
if (rootPath != null && rootPath != _lastProjectRoot) {
if (rootPath != _lastProjectRoot) {
_lastProjectRoot = rootPath;
if (rootPath != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
runProvider?.onProjectOpened(rootPath, activeFilePath: currentFile);
}
});
} else {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
runProvider?.onProjectClosed();
}
});
}
}
return PopScope(
canPop: !isModified,
canPop: false,
onPopInvokedWithResult: (didPop, result) async {
if (didPop) return;
final canProceed = await _getTabProvider(context).checkUnsavedChanges(context);
if (canProceed && context.mounted) {
Navigator.of(context).pop();
final nav = Navigator.of(context);
if (nav.canPop()) {
nav.pop();
} else {
await SystemNavigator.pop();
}
}
},
child: Scaffold(
+376
View File
@@ -0,0 +1,376 @@
import 'dart:io';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/providers/project_provider.dart';
import 'package:code_editor/providers/tab_provider.dart';
import 'package:code_editor/services/internal_project_service.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
/// 内部存储项目管理页面 (files/projects)
class ProjectManagementView extends StatefulWidget {
const ProjectManagementView({super.key});
@override
State<ProjectManagementView> createState() => _ProjectManagementViewState();
}
class _ProjectManagementViewState extends State<ProjectManagementView> {
final InternalProjectService _projectService = InternalProjectService.instance;
List<Directory> _projects = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadProjects();
}
static ProjectProvider _getProjectProvider(BuildContext context, {bool listen = false}) {
return listen ? context.watch<ProjectProvider>() : context.read<ProjectProvider>();
}
static TabProvider _getTabProvider(BuildContext context, {bool listen = false}) {
return listen ? context.watch<TabProvider>() : context.read<TabProvider>();
}
Future<void> _loadProjects() async {
final list = await _projectService.listProjects();
if (mounted) {
setState(() {
_projects = list;
_isLoading = false;
});
}
}
bool _isValidProjectArchive(String path) {
final lower = path.toLowerCase();
return lower.endsWith('.zip') ||
lower.endsWith('.tar.gz') ||
lower.endsWith('.tgz') ||
lower.endsWith('.tar.xz') ||
lower.endsWith('.txz') ||
lower.endsWith('.tar.bz2') ||
lower.endsWith('.tbz') ||
lower.endsWith('.tbz2') ||
lower.endsWith('.tar');
}
Future<void> _onImportProject() async {
final l10n = AppLocalizations.of(context)!;
// 1. 打开手机系统文件管理选择一个压缩文件(限制为常用压缩格式)
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: const ['zip', 'tar', 'gz', 'tgz', 'xz', 'txz', 'bz2', 'tbz'],
);
if (result == null || result.files.isEmpty || !mounted) return;
final filePath = result.files.single.path;
if (filePath == null || filePath.trim().isEmpty || !mounted) return;
// 校验文件格式是否属于受支持的压缩包格式
if (!_isValidProjectArchive(filePath)) {
if (mounted) {
DialogUtils.showErrorToast(context, l10n.unsupportedProjectArchiveFormat);
}
return;
}
// 2. 提取压缩包默认项目名称(去除 .tar.gz, .tgz, .zip 等扩展名)
String defaultName = p.basename(filePath);
if (defaultName.endsWith('.tar.gz')) {
defaultName = defaultName.substring(0, defaultName.length - 7);
} else if (defaultName.endsWith('.tar.xz')) {
defaultName = defaultName.substring(0, defaultName.length - 7);
} else if (defaultName.endsWith('.tgz')) {
defaultName = defaultName.substring(0, defaultName.length - 4);
} else {
defaultName = p.basenameWithoutExtension(filePath);
}
defaultName = defaultName.trim();
// 3. 弹出一个 dialog,让用户确定项目名称
final confirmedName = await DialogUtils.showInputDialog(
context,
title: l10n.confirmProjectNameTitle,
hintText: l10n.projectNameHint,
initialValue: defaultName,
validator: (val) {
if (val == null || val.trim().isEmpty) {
return l10n.nameCannotBeEmpty;
}
if (val.contains(RegExp(r'[\\/:*?"<>|]'))) {
return l10n.nameInvalidChars;
}
return null;
},
);
if (confirmedName == null || confirmedName.trim().isEmpty || !mounted) {
return;
}
final trimmedName = confirmedName.trim();
if (await _projectService.projectExists(trimmedName)) {
if (mounted) {
DialogUtils.showErrorToast(context, l10n.projectAlreadyExists);
}
return;
}
// 4. 注意:确定项目名称之后才去进行解压复制操作
if (!mounted) return;
try {
await DialogUtils.showSyncLoadingDialog(
context,
message: l10n.importingProject,
task: () async {
await _projectService.importProjectFromArchive(filePath, trimmedName);
},
);
if (mounted) {
DialogUtils.showSuccessToast(context, l10n.projectImported);
await _loadProjects();
}
} catch (e) {
if (mounted) {
DialogUtils.showErrorToast(
context,
l10n.importProjectFailed(e.toString()),
);
}
}
}
Future<void> _onCreateProject() async {
final l10n = AppLocalizations.of(context)!;
final name = await DialogUtils.showInputDialog(
context,
title: l10n.newProjectTitle,
hintText: l10n.projectNameHint,
validator: (val) {
if (val == null || val.trim().isEmpty) {
return l10n.nameCannotBeEmpty;
}
if (val.contains(RegExp(r'[\\/:*?"<>|]'))) {
return l10n.nameInvalidChars;
}
return null;
},
);
if (name == null || name.trim().isEmpty || !mounted) return;
final trimmedName = name.trim();
if (await _projectService.projectExists(trimmedName)) {
if (mounted) {
DialogUtils.showErrorToast(context, l10n.projectAlreadyExists);
}
return;
}
try {
await _projectService.createProject(trimmedName);
if (mounted) {
DialogUtils.showSuccessToast(context, l10n.projectCreated);
await _loadProjects();
}
} catch (e) {
if (mounted) {
DialogUtils.showErrorToast(context, e.toString());
}
}
}
Future<void> _onRenameProject(Directory dir, String currentName) async {
final l10n = AppLocalizations.of(context)!;
final newName = await DialogUtils.showInputDialog(
context,
title: l10n.renameProject,
hintText: l10n.projectNameHint,
initialValue: currentName,
validator: (val) {
if (val == null || val.trim().isEmpty) {
return l10n.nameCannotBeEmpty;
}
if (val.contains(RegExp(r'[\\/:*?"<>|]'))) {
return l10n.nameInvalidChars;
}
return null;
},
);
if (newName == null || newName.trim().isEmpty || newName.trim() == currentName || !mounted) {
return;
}
final trimmedName = newName.trim();
if (await _projectService.projectExists(trimmedName)) {
if (mounted) {
DialogUtils.showErrorToast(context, l10n.projectAlreadyExists);
}
return;
}
if (!mounted) return;
final projectProvider = _getProjectProvider(context);
try {
final newDir = await _projectService.renameProject(dir, trimmedName);
if (projectProvider.rootPath != null &&
p.normalize(projectProvider.rootPath!) == p.normalize(dir.path)) {
await projectProvider.openSpecificDirectory(newDir.path);
}
if (mounted) {
DialogUtils.showSuccessToast(context, l10n.projectRenamed);
await _loadProjects();
}
} catch (e) {
if (mounted) {
DialogUtils.showErrorToast(context, e.toString());
}
}
}
Future<void> _onDeleteProject(Directory dir, String projectName) async {
final l10n = AppLocalizations.of(context)!;
final confirmed = await DialogUtils.showDestructiveConfirmDialog(
context,
title: l10n.deleteProject,
message: l10n.deleteProjectConfirmMessage(projectName),
confirmText: l10n.delete,
cancelText: l10n.cancel,
);
if (!confirmed || !mounted) return;
final projectProvider = _getProjectProvider(context);
try {
await _projectService.deleteProject(dir);
if (projectProvider.rootPath != null &&
p.normalize(projectProvider.rootPath!) == p.normalize(dir.path)) {
await projectProvider.closeProject();
}
if (mounted) {
DialogUtils.showSuccessToast(context, l10n.projectDeleted);
await _loadProjects();
}
} catch (e) {
if (mounted) {
DialogUtils.showErrorToast(context, e.toString());
}
}
}
Future<void> _onOpenProject(Directory dir) async {
final tabProvider = _getTabProvider(context);
final projectProvider = _getProjectProvider(context);
final canProceed = await tabProvider.checkUnsavedChanges(context);
if (!canProceed || !mounted) return;
await projectProvider.openSpecificDirectory(dir.path);
if (mounted) {
Navigator.of(context).pop();
}
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: Text(
l10n.projectsTitle,
style: const TextStyle(fontWeight: FontWeight.bold),
),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: l10n.back,
onPressed: () => Navigator.of(context).pop(),
),
actions: [
IconButton(
icon: const Icon(Icons.file_upload_outlined),
tooltip: l10n.importFromExternal,
onPressed: _onImportProject,
),
IconButton(
icon: const Icon(Icons.add),
tooltip: l10n.newProject,
onPressed: _onCreateProject,
),
const SizedBox(width: 4),
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _projects.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.folder_open_outlined,
size: 64,
color: theme.colorScheme.outline,
),
const SizedBox(height: 16),
Text(
l10n.noProjects,
style: TextStyle(
color: theme.colorScheme.outline,
fontSize: 14,
),
),
],
),
)
: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
itemCount: _projects.length,
itemBuilder: (context, index) {
final dir = _projects[index];
final projectName = p.basename(dir.path);
return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
leading: Icon(
Icons.folder,
color: theme.colorScheme.primary,
),
title: Text(
projectName,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.edit_outlined),
tooltip: l10n.renameProject,
onPressed: () => _onRenameProject(dir, projectName),
),
IconButton(
icon: const Icon(Icons.delete_outline),
tooltip: l10n.deleteProject,
onPressed: () => _onDeleteProject(dir, projectName),
),
],
),
onTap: () => _onOpenProject(dir),
);
},
),
);
}
}
+3 -1
View File
@@ -175,11 +175,13 @@ class _RunTaskDetailViewState extends State<RunTaskDetailView> {
const SizedBox(height: 16),
TextFormField(
controller: _commandController,
maxLines: 4,
minLines: 3,
maxLines: 8,
style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
decoration: InputDecoration(
labelText: l10n.shellCommandRequired,
hintText: l10n.shellCommandHint,
helperText: l10n.shellCommandHelperText,
border: const OutlineInputBorder(),
alignLabelWithHint: true,
isDense: true,
+3 -3
View File
@@ -272,14 +272,14 @@ class _RunTaskEditViewState extends State<RunTaskEditView> {
),
// 只显示:名称 + 用途(描述)
title: Text(
task.name,
task.getLocalizedName(l10n),
style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: (task.description != null && task.description!.trim().isNotEmpty)
subtitle: task.getLocalizedDescription(l10n).trim().isNotEmpty
? Text(
task.description!.trim(),
task.getLocalizedDescription(l10n).trim(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.colorScheme.outline),
+104 -1
View File
@@ -1,5 +1,6 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/models/editor_theme.dart';
import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:code_editor/providers/settings_provider.dart';
@@ -78,7 +79,15 @@ class SettingsView extends StatelessWidget {
const Divider(height: 32, indent: 16, endIndent: 16),
// ==============================
// 5. 语言分组 (Language)
// 5. 下载分组 (Download)
// ==============================
_buildSectionHeader(context, l10n.downloadSection),
_buildDownloadSourceTile(context, provider, l10n),
const Divider(height: 32, indent: 16, endIndent: 16),
// ==============================
// 6. 语言分组 (Language)
// ==============================
_buildSectionHeader(context, l10n.languageSection),
_buildLanguageTile(context, provider, l10n),
@@ -940,4 +949,98 @@ class SettingsView extends StatelessWidget {
},
);
}
/// 下载:下载源设置条目
Widget _buildDownloadSourceTile(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
final theme = Theme.of(context);
final currentMirrorId = provider.downloadMirrorId;
return ListTile(
leading: Icon(Icons.cloud_download_outlined, color: theme.colorScheme.primary),
title: Text(l10n.downloadSource),
subtitle: Text(l10n.mirrorName(currentMirrorId)),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showDownloadSourceSelector(context, provider, l10n);
},
);
}
/// 显示下载源底部选择器(与字体选择器一致的弹窗体验)
void _showDownloadSourceSelector(
BuildContext context,
SettingsProvider provider,
AppLocalizations l10n,
) {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (sheetContext) {
final theme = Theme.of(context);
final mirrors = DistroRepository.availableMirrors;
return SafeArea(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(sheetContext).size.height * 0.65,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
l10n.selectDownloadSource,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
const Divider(height: 1),
Expanded(
child: ListView.builder(
itemCount: mirrors.length,
itemBuilder: (context, index) {
final item = mirrors[index];
final isSelected = item.id == provider.downloadMirrorId;
return ListTile(
leading: Icon(
Icons.dns_outlined,
color: isSelected ? theme.colorScheme.primary : null,
),
title: Text(
l10n.mirrorName(item.id),
style: TextStyle(
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
color: isSelected ? theme.colorScheme.primary : null,
),
),
subtitle: Text(
item.baseUrl,
style: TextStyle(
fontSize: 12.0,
color: theme.colorScheme.onSurfaceVariant,
),
),
trailing: isSelected
? Icon(Icons.check, color: theme.colorScheme.primary)
: null,
onTap: () {
provider.setDownloadMirrorId(item.id);
Navigator.of(sheetContext).pop();
},
);
},
),
),
],
),
),
);
},
);
}
}
+19 -11
View File
@@ -1,5 +1,6 @@
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/app_font.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/models/terminal_session.dart';
import 'package:code_editor/models/virtual_keyboard_config.dart';
import 'package:code_editor/providers/distro_provider.dart';
@@ -39,8 +40,13 @@ class _TerminalViewState extends State<TerminalView> {
final l10n = AppLocalizations.of(context)!;
final defaultSessionName = l10n.sessionDefaultName;
final projectRoot = context.read<ProjectProvider?>()?.rootPath;
if (distroProvider == null) {
context.read<TerminalProvider>().ensureInitialized(defaultName: defaultSessionName);
context.read<TerminalProvider>().ensureInitialized(
defaultName: defaultSessionName,
workspacePath: projectRoot,
);
return;
}
@@ -48,13 +54,13 @@ class _TerminalViewState extends State<TerminalView> {
if (!mounted) return;
if (!distroProvider.hasAnySystem) {
// 自动从软件内置资源导入 alpine,名称即为 alpine
// 自动从软件内置资源导入 Ubuntu 24.04(推荐主力开发环境),名称为 ubuntu
final success = await DistroExtractDialog.show(
context: context,
systemName: 'alpine',
systemName: DistroRepository.defaultSystemName,
task: (onProgress, isCancelled) {
return distroProvider.importBuiltinAlpine(
systemName: 'alpine',
return distroProvider.importBuiltinUbuntu(
systemName: DistroRepository.defaultSystemName,
onProgress: onProgress,
isCancelled: isCancelled,
);
@@ -66,7 +72,8 @@ class _TerminalViewState extends State<TerminalView> {
if (termProvider.isEmpty) {
termProvider.createSession(
name: defaultSessionName,
distroId: 'alpine',
distroId: DistroRepository.defaultSystemName,
workspacePath: projectRoot,
activate: true,
);
}
@@ -75,10 +82,11 @@ class _TerminalViewState extends State<TerminalView> {
// 已有系统,确保初始化首个会话
final termProvider = context.read<TerminalProvider>();
if (termProvider.isEmpty) {
final system = distroProvider.selectedSystem ?? 'alpine';
final system = distroProvider.selectedSystem ?? DistroRepository.defaultSystemName;
termProvider.createSession(
name: defaultSessionName,
distroId: system,
workspacePath: projectRoot,
activate: true,
);
}
@@ -91,16 +99,16 @@ class _TerminalViewState extends State<TerminalView> {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final provider = context.watch<TerminalProvider>();
final projectProvider = context.watch<ProjectProvider?>();
final activeSession = provider.activeSession;
final sessions = provider.sessions;
final activeIndex = provider.activeIndex;
final titleText = activeSession?.name ?? l10n.sessionDefaultName;
final projectRoot = activeSession?.workspacePath ?? projectProvider?.rootPath;
final String? subtitleText = (projectRoot != null && projectRoot.trim().isNotEmpty)
? projectRoot.trim()
// 副标题严格取自当前会话绑定的工作目录根路径
final sessionWorkspace = activeSession?.workspacePath;
final String? subtitleText = (sessionWorkspace != null && sessionWorkspace.trim().isNotEmpty)
? sessionWorkspace.trim()
: null;
return Scaffold(
+58 -5
View File
@@ -1,14 +1,22 @@
import 'package:code_editor/l10n/app_localizations.dart';
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/services/internal_project_service.dart';
import 'package:code_editor/services/permission_service.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/views/project_management_view.dart';
import 'package:code_editor/widgets/project_history_widget.dart';
import 'package:code_editor/widgets/file_tree_widget.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
enum _OpenProjectSource {
fromApp,
fromExternal,
}
class CodeEditorDrawer extends StatelessWidget {
const CodeEditorDrawer({super.key});
@@ -119,13 +127,51 @@ class CodeEditorDrawer extends StatelessWidget {
IconButton(
icon: const Icon(Icons.refresh),
tooltip: l10n.refreshDirectory,
onPressed: () =>
_getProjectProvider(context).refreshTree(),
onPressed: () {
_getProjectProvider(context).refreshTree();
final runProvider = context.read<RunProvider?>();
final root = _getProjectProvider(context).rootPath;
if (root != null && root.isNotEmpty) {
runProvider?.onProjectOpened(root);
}
},
),
IconButton(
PopupMenuButton<_OpenProjectSource>(
icon: const Icon(Icons.folder_open),
tooltip: l10n.openFileDirectory,
onPressed: () async {
itemBuilder: (popupContext) => [
PopupMenuItem<_OpenProjectSource>(
value: _OpenProjectSource.fromApp,
child: Row(
children: [
const Icon(Icons.inventory_2_outlined, size: 20),
const SizedBox(width: 8),
Text(l10n.openFromApp),
],
),
),
PopupMenuItem<_OpenProjectSource>(
value: _OpenProjectSource.fromExternal,
child: Row(
children: [
const Icon(Icons.folder_open_outlined, size: 20),
const SizedBox(width: 8),
Text(l10n.openFromExternal),
],
),
),
],
onSelected: (source) async {
switch (source) {
case _OpenProjectSource.fromApp:
Navigator.of(context).pop();
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const ProjectManagementView(),
),
);
break;
case _OpenProjectSource.fromExternal:
final hasPermission = await PermissionService
.instance
.ensureStoragePermission(context: context);
@@ -135,6 +181,8 @@ class CodeEditorDrawer extends StatelessWidget {
).checkUnsavedChanges(context);
if (!canProceed || !context.mounted) return;
_getProjectProvider(context).openDirectory();
break;
}
},
),
IconButton(
@@ -161,7 +209,12 @@ class CodeEditorDrawer extends StatelessWidget {
children: [
Expanded(
child: Text(
rootPath ?? '',
hasProject
? (InternalProjectService.instance
.isInternalProject(rootPath)
? p.basename(rootPath)
: rootPath)
: '',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
+85 -31
View File
@@ -2,7 +2,10 @@ import 'dart:io';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/services/distro_download_manager.dart';
import 'package:code_editor/utils/dialog_utils.dart';
import 'package:code_editor/views/distro_management_view.dart';
import 'package:code_editor/widgets/distro_extract_dialog.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
@@ -55,14 +58,14 @@ class DistroSelectorDialog extends StatelessWidget {
onSelected: (action) => _handleImportAction(context, action),
itemBuilder: (context) => [
PopupMenuItem(
value: 'builtin',
value: 'management_view',
child: Row(
children: [
const Icon(Icons.layers_outlined, size: 18),
const Icon(Icons.apps_rounded, size: 18),
const SizedBox(width: 8),
Flexible(
child: Text(
l10n.importBuiltinAlpine,
l10n.importFromApp,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
@@ -197,47 +200,46 @@ class DistroSelectorDialog extends StatelessWidget {
}
/// 处理导入菜单操作
bool _isValidDistroArchive(String path) {
final lower = path.toLowerCase();
return lower.endsWith('.tar.gz') ||
lower.endsWith('.tgz') ||
lower.endsWith('.tar.xz') ||
lower.endsWith('.txz') ||
lower.endsWith('.tar');
}
Future<void> _handleImportAction(BuildContext context, String action) async {
final distroProvider = context.read<DistroProvider>();
final l10n = AppLocalizations.of(context)!;
if (action == 'builtin') {
// 1. 从内置 Alpine 导入
final defaultName = _generateUniqueSystemName('alpine', distroProvider.installedSystems);
final systemName = await DialogUtils.showInputDialog(
context,
title: l10n.importBuiltinAlpineTitle,
hintText: l10n.systemNameHintWithDefault(defaultName),
initialValue: defaultName,
if (action == 'management_view') {
// 1. 跳转到应用内系统管理页面
final selectedItem = await Navigator.of(context).push<DistroManifestItem>(
MaterialPageRoute(builder: (_) => const DistroManagementView()),
);
if (systemName == null || systemName.trim().isEmpty || !context.mounted) return;
final cleanName = systemName.trim();
// 模态同步解压
final success = await DistroExtractDialog.show(
context: context,
systemName: cleanName,
task: (onProgress, isCancelled) {
return distroProvider.importBuiltinAlpine(
systemName: cleanName,
onProgress: onProgress,
isCancelled: isCancelled,
);
},
);
if (success && context.mounted) {
DialogUtils.showSuccessToast(context, l10n.systemImportSuccess(cleanName));
if (selectedItem != null && context.mounted) {
// 用户直接点击已经安装的 item 本身,代表用户选择了那个 zip,返回后解压创建系统
await _handleCreateSystemFromManifest(context, selectedItem);
}
} else if (action == 'external') {
// 2. 从外部选择 .tar.gz 压缩包导入
// 2. 从外部选择 .tar.gz / .tar.xz 压缩包导入
final result = await FilePicker.platform.pickFiles(
type: FileType.any,
type: FileType.custom,
allowedExtensions: const ['tar', 'gz', 'tgz', 'xz', 'txz'],
);
if (result == null || result.files.single.path == null || !context.mounted) return;
final filePath = result.files.single.path!;
if (!_isValidDistroArchive(filePath)) {
if (context.mounted) {
DialogUtils.showErrorToast(context, l10n.unsupportedDistroArchiveFormat);
}
return;
}
final file = File(filePath);
// 提取默认名称(去掉 .tar.gz, .tgz 等后缀)
@@ -284,6 +286,58 @@ class DistroSelectorDialog extends StatelessWidget {
}
}
/// 从选中的发行版安装包解压创建新的系统实例
Future<void> _handleCreateSystemFromManifest(BuildContext context, DistroManifestItem item) async {
final distroProvider = context.read<DistroProvider>();
final l10n = AppLocalizations.of(context)!;
final defaultName = _generateUniqueSystemName(item.id, distroProvider.installedSystems);
final systemName = await DialogUtils.showInputDialog(
context,
title: l10n.importSystemInstanceTitle(item.name),
hintText: l10n.systemNameHintWithDefault(defaultName),
initialValue: defaultName,
);
if (systemName == null || systemName.trim().isEmpty || !context.mounted) return;
final cleanName = systemName.trim();
// 模态同步解压
final success = await DistroExtractDialog.show(
context: context,
systemName: cleanName,
task: (onProgress, isCancelled) async {
if (item.id == 'ubuntu') {
return distroProvider.importBuiltinUbuntu(
systemName: cleanName,
onProgress: onProgress,
isCancelled: isCancelled,
);
} else if (item.id == 'alpine') {
return distroProvider.importBuiltinAlpine(
systemName: cleanName,
onProgress: onProgress,
isCancelled: isCancelled,
);
} else {
final file = await DistroDownloadManager().getPackageFile(item.id, item.currentPackageSource!);
return distroProvider.importFromCustomTarGz(
systemName: cleanName,
tarGzFile: file,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
},
);
if (success && context.mounted) {
DialogUtils.showSuccessToast(context, l10n.systemImportSuccess(cleanName));
await distroProvider.refreshSystems();
await distroProvider.selectSystem(cleanName);
}
}
/// 高危操作:二次确认删除系统
Future<void> _handleDeleteSystem(BuildContext context, String systemName) async {
final l10n = AppLocalizations.of(context)!;
+15 -10
View File
@@ -63,10 +63,13 @@ class _RunTasksDialogState extends State<RunTasksDialog> {
super.dispose();
}
bool _matchesQuery(RunTask task) {
bool _matchesQuery(RunTask task, AppLocalizations l10n) {
if (_searchQuery.isEmpty) return true;
return task.name.toLowerCase().contains(_searchQuery) ||
final name = task.getLocalizedName(l10n);
final desc = task.getLocalizedDescription(l10n);
return name.toLowerCase().contains(_searchQuery) ||
task.command.toLowerCase().contains(_searchQuery) ||
desc.toLowerCase().contains(_searchQuery) ||
(task.description?.toLowerCase().contains(_searchQuery) ?? false);
}
@@ -74,8 +77,8 @@ class _RunTasksDialogState extends State<RunTasksDialog> {
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = AppLocalizations.of(context)!;
final filteredCustom = widget.customTasks.where(_matchesQuery).toList();
final filteredDetected = widget.detectedTasks.where(_matchesQuery).toList();
final filteredCustom = widget.customTasks.where((t) => _matchesQuery(t, l10n)).toList();
final filteredDetected = widget.detectedTasks.where((t) => _matchesQuery(t, l10n)).toList();
final hasAny = filteredCustom.isNotEmpty || filteredDetected.isNotEmpty;
return Dialog(
@@ -146,12 +149,12 @@ class _RunTasksDialogState extends State<RunTasksDialog> {
children: [
if (filteredDetected.isNotEmpty) ...[
_buildSectionHeader(context, l10n.systemDetectedTasks, Icons.radar_outlined),
...filteredDetected.map((task) => _buildTaskItem(context, task)),
...filteredDetected.map((task) => _buildTaskItem(context, task, l10n)),
const SizedBox(height: 8),
],
if (filteredCustom.isNotEmpty) ...[
_buildSectionHeader(context, l10n.userCustomTasks, Icons.person_outline),
...filteredCustom.map((task) => _buildTaskItem(context, task)),
...filteredCustom.map((task) => _buildTaskItem(context, task, l10n)),
],
],
),
@@ -183,7 +186,7 @@ class _RunTasksDialogState extends State<RunTasksDialog> {
);
}
Widget _buildTaskItem(BuildContext context, RunTask task) {
Widget _buildTaskItem(BuildContext context, RunTask task, AppLocalizations l10n) {
final theme = Theme.of(context);
final isLastRun = widget.lastRunTaskId != null && widget.lastRunTaskId == task.id;
@@ -195,6 +198,8 @@ class _RunTasksDialogState extends State<RunTasksDialog> {
? Colors.green.withValues(alpha: 0.8)
: theme.colorScheme.outlineVariant.withValues(alpha: 0.5);
final localizedDesc = task.getLocalizedDescription(l10n).trim();
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
elevation: 0,
@@ -210,7 +215,7 @@ class _RunTasksDialogState extends State<RunTasksDialog> {
children: [
Expanded(
child: Text(
task.name,
task.getLocalizedName(l10n),
style: TextStyle(
fontWeight: FontWeight.w600,
color: isLastRun ? Colors.green.shade700 : null,
@@ -233,9 +238,9 @@ class _RunTasksDialogState extends State<RunTasksDialog> {
),
],
),
subtitle: (task.description != null && task.description!.trim().isNotEmpty)
subtitle: localizedDesc.isNotEmpty
? Text(
task.description!.trim(),
localizedDesc,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
+2
View File
@@ -44,8 +44,10 @@ flutter:
assets:
- assets/distros/
- assets/certs/
- assets/shims/x86_64/
- assets/shims/arm64-v8a/
- assets/icons/distros/
fonts:
- family: JetBrains Mono
+401
View File
@@ -0,0 +1,401 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:archive/archive.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/services/distro_image_resolver.dart';
import 'package:code_editor/services/distro_installer.dart';
import 'package:code_editor/services/low_memory_xz_decoder.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const sampleIndexSystem = '''
# LXC Images Mirror index
debian;bookworm;arm64;default;20260912_05:24;/images/debian/bookworm/arm64/default/20260912_05:24/
debian;bookworm;arm64;default;20260913_05:24;/images/debian/bookworm/arm64/default/20260913_05:24/
debian;bookworm;amd64;default;20260913_05:24;/images/debian/bookworm/amd64/default/20260913_05:24/
archlinux;current;arm64;default;20260913_04:18;/images/archlinux/current/arm64/default/20260913_04:18/
archlinux;current;amd64;default;20260913_04:18;/images/archlinux/current/amd64/default/20260913_04:18/
fedora;43;arm64;default;20260913_20:33;/images/fedora/43/arm64/default/20260913_20:33/
fedora;43;amd64;default;20260913_20:33;/images/fedora/43/amd64/default/20260913_20:33/
''';
group('DistroIndexEntry & DistroImageResolver Tests', () {
late DistroImageResolver resolver;
setUp(() {
resolver = DistroImageResolver();
resolver.invalidateCache();
resolver.customIndexContent = sampleIndexSystem;
});
tearDown(() {
resolver.customIndexContent = null;
resolver.invalidateCache();
});
test('parseIndex extracts all valid entries', () {
final entries = DistroImageResolver.parseIndex(sampleIndexSystem);
expect(entries.length, 7);
expect(entries.first.distribution, 'debian');
expect(entries.first.release, 'bookworm');
expect(entries.first.arch, 'arm64');
expect(entries.first.variant, 'default');
expect(entries.first.buildDate, '20260912_05:24');
expect(entries.first.path, '/images/debian/bookworm/arm64/default/20260912_05:24/');
});
test('toLxcArch maps arm64 and x86_64 correctly', () {
expect(DistroImageResolver.toLxcArch(DistroArch.arm64), 'arm64');
expect(DistroImageResolver.toLxcArch(DistroArch.x86_64), 'amd64');
});
test('resolveDownloadUrl picks latest build date for debian arm64', () async {
final debian = DistroRepository.getById('debian')!;
final tsinghua = DistroRepository.getMirrorById('tsinghua');
final url = await resolver.resolveDownloadUrl(
item: debian,
arch: DistroArch.arm64,
mirror: tsinghua,
);
// 应该选择 20260913_05:24 而不是旧的 20260912_05:24
expect(
url,
'https://mirrors.tuna.tsinghua.edu.cn/lxc-images/images/debian/bookworm/arm64/default/20260913_05:24/rootfs.tar.xz',
);
});
test('resolveDownloadUrl resolves archlinux on different mirrors', () async {
final arch = DistroRepository.getById('arch')!;
final bfsu = DistroRepository.getMirrorById('bfsu');
final url = await resolver.resolveDownloadUrl(
item: arch,
arch: DistroArch.x86_64,
mirror: bfsu,
);
expect(
url,
'https://mirrors.bfsu.edu.cn/lxc-images/images/archlinux/current/amd64/default/20260913_04:18/rootfs.tar.xz',
);
});
test('resolveDownloadUrl resolves fedora 43 arm64', () async {
final fedora = DistroRepository.getById('fedora')!;
final iscas = DistroRepository.getMirrorById('iscas');
final url = await resolver.resolveDownloadUrl(
item: fedora,
arch: DistroArch.arm64,
mirror: iscas,
);
expect(
url,
'https://mirror.iscas.ac.cn/lxc-images/images/fedora/43/arm64/default/20260913_20:33/rootfs.tar.xz',
);
});
test('resolveDownloadUrl throws HttpException when image is not in index', () async {
const emptyIndex = '# Empty index\n';
resolver.customIndexContent = emptyIndex;
final debian = DistroRepository.getById('debian')!;
final tsinghua = DistroRepository.getMirrorById('tsinghua');
expect(
() => resolver.resolveDownloadUrl(
item: debian,
arch: DistroArch.arm64,
mirror: tsinghua,
),
throwsA(isA<HttpException>()),
);
});
test('resolveDownloadUrl returns builtin asset path directly for builtin distro', () async {
final alpine = DistroRepository.getById('alpine')!;
final tsinghua = DistroRepository.getMirrorById('tsinghua');
final url = await resolver.resolveDownloadUrl(
item: alpine,
arch: DistroArch.arm64,
mirror: tsinghua,
);
expect(url, 'assets/distros/alpine-minirootfs-3.20.3-aarch64.tar.gz');
});
});
group('DistroInstaller Archive Decoding Tests', () {
test('installFromBytes succeeds with valid TarGz archive bytes', () async {
// 创建包含一个测试文件的 TarGz 内存包
final archive = Archive();
archive.addFile(ArchiveFile('test.txt', 5, utf8.encode('hello')));
final tarBytes = TarEncoder().encode(archive);
final gzBytes = Uint8List.fromList(GZipEncoder().encode(tarBytes)!);
final tempDir = Directory.systemTemp.createTempSync('installer_test_');
try {
await DistroInstaller.installFromBytes(
tarGzBytes: gzBytes,
targetDir: tempDir,
);
final testFile = File('${tempDir.path}/test.txt');
expect(testFile.existsSync(), isTrue);
expect(testFile.readAsStringSync(), 'hello');
} finally {
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
}
});
test('installFromBytes succeeds with valid TarXZ archive bytes', () async {
// 创建包含一个测试文件的 TarXZ 内存包
final archive = Archive();
archive.addFile(ArchiveFile('greet.txt', 5, utf8.encode('world')));
final tarBytes = TarEncoder().encode(archive);
final xzBytes = encodeValidXz(tarBytes);
final tempDir = Directory.systemTemp.createTempSync('installer_xz_test_');
try {
await DistroInstaller.installFromBytes(
tarGzBytes: xzBytes,
targetDir: tempDir,
);
final testFile = File('${tempDir.path}/greet.txt');
expect(testFile.existsSync(), isTrue);
expect(testFile.readAsStringSync(), 'world');
} finally {
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
}
});
test('installFromFile directly extracts TarXZ file on disk', () async {
final archive = Archive();
archive.addFile(ArchiveFile('direct.txt', 6, utf8.encode('direct')));
final tarBytes = TarEncoder().encode(archive);
final xzBytes = encodeValidXz(tarBytes);
final tempDir = Directory.systemTemp.createTempSync('installer_file_test_');
final archiveFile = File('${tempDir.path}/test.tar.xz');
archiveFile.writeAsBytesSync(xzBytes);
final outDir = Directory('${tempDir.path}/rootfs');
try {
await DistroInstaller.installFromFile(
archiveFile: archiveFile,
targetDir: outDir,
);
final testFile = File('${outDir.path}/direct.txt');
expect(testFile.existsSync(), isTrue);
expect(testFile.readAsStringSync(), 'direct');
} finally {
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
}
});
test('installFromFile cancellation throws DistroInstallCancelledException and rolls back targetDir', () async {
final archive = Archive();
archive.addFile(ArchiveFile('cancel.txt', 6, utf8.encode('cancel')));
final tarBytes = TarEncoder().encode(archive);
final xzBytes = encodeValidXz(tarBytes);
final tempDir = Directory.systemTemp.createTempSync('installer_cancel_test_');
final archiveFile = File('${tempDir.path}/test.tar.xz');
archiveFile.writeAsBytesSync(xzBytes);
final outDir = Directory('${tempDir.path}/rootfs');
try {
expect(
() => DistroInstaller.installFromFile(
archiveFile: archiveFile,
targetDir: outDir,
isCancelled: () => true,
),
throwsA(isA<DistroInstallCancelledException>()),
);
// 验证回滚:目标目录不残留
expect(outDir.existsSync(), isFalse);
} finally {
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
}
});
test('LowMemoryXZDecoder decodes valid XZ stream directly to sink', () async {
final inputBytes = utf8.encode('Low memory streaming XZ decoding test string! 1234567890');
final xzBytes = encodeValidXz(inputBytes);
final tempDir = Directory.systemTemp.createTempSync('low_mem_xz_test_');
final outFile = File('${tempDir.path}/out.bin');
final outSink = outFile.openWrite();
final decoder = LowMemoryXZDecoder();
var progressFired = false;
try {
decoder.decodeToSink(
InputStream(xzBytes),
outSink,
onProgress: (decompressed, compPos) {
progressFired = true;
},
);
} finally {
await outSink.flush();
await outSink.close();
}
expect(outFile.existsSync(), isTrue);
expect(outFile.readAsBytesSync(), inputBytes);
expect(progressFired, isTrue);
tempDir.deleteSync(recursive: true);
});
test('installFromFile extracts multiple files, subdirectories and reports progress', () async {
final archive = Archive();
archive.addFile(ArchiveFile('sub/dir/one.txt', 5, utf8.encode('one..')));
archive.addFile(ArchiveFile('sub/dir/two.txt', 5, utf8.encode('two..')));
archive.addFile(ArchiveFile('root.txt', 4, utf8.encode('root')));
final tarBytes = TarEncoder().encode(archive);
final xzBytes = encodeValidXz(tarBytes);
final tempDir = Directory.systemTemp.createTempSync('installer_multi_test_');
final archiveFile = File('${tempDir.path}/distro.tar.xz');
archiveFile.writeAsBytesSync(xzBytes);
final outDir = Directory('${tempDir.path}/rootfs');
final progressList = <double>[];
try {
await DistroInstaller.installFromFile(
archiveFile: archiveFile,
targetDir: outDir,
onProgress: (prog, msg) {
progressList.add(prog);
},
);
expect(File('${outDir.path}/sub/dir/one.txt').readAsStringSync(), 'one..');
expect(File('${outDir.path}/sub/dir/two.txt').readAsStringSync(), 'two..');
expect(File('${outDir.path}/root.txt').readAsStringSync(), 'root');
expect(progressList.isNotEmpty, isTrue);
expect(progressList.last, 1.0);
} finally {
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
}
});
});
}
/// 遵循标准 LEB128 与 XZ 格式的纯 Dart 辅助编码器(避免 archive 包中 XZEncoder 的多字节大端序 bug)
Uint8List encodeValidXz(List<int> data) {
void writeLeb128(BytesBuilder out, int value) {
while (value >= 0x80) {
out.addByte((value & 0x7f) | 0x80);
value >>= 7;
}
out.addByte(value & 0x7f);
}
final out = BytesBuilder();
out.add([253, 55, 122, 88, 90, 0]); // Header magic
final headerFlags = [0, 0];
out.add(headerFlags);
final headerCrc = getCrc32(headerFlags);
out.add([headerCrc & 0xff, (headerCrc >> 8) & 0xff, (headerCrc >> 16) & 0xff, (headerCrc >> 24) & 0xff]);
final lzma2 = BytesBuilder();
var offset = 0;
var isFirst = true;
while (offset < data.length) {
final chunkLen = (data.length - offset).clamp(1, 65536);
lzma2.addByte(isFirst ? 1 : 2);
isFirst = false;
final lenMinusOne = chunkLen - 1;
lzma2.addByte((lenMinusOne >> 8) & 0xff);
lzma2.addByte(lenMinusOne & 0xff);
lzma2.add(data.sublist(offset, offset + chunkLen));
offset += chunkLen;
}
lzma2.addByte(0); // end marker
final lzma2Bytes = lzma2.toBytes();
final filter = BytesBuilder();
writeLeb128(filter, 0x21); // LZMA2
writeLeb128(filter, 1);
filter.addByte(0); // dict size
final filterBytes = filter.toBytes();
final headerSizeWithoutCrc = 1 + 1 + filterBytes.length;
final paddingHeader = (4 - ((headerSizeWithoutCrc + 4) % 4)) % 4;
final totalHeaderSize = headerSizeWithoutCrc + paddingHeader + 4;
final blockHeader = BytesBuilder();
blockHeader.addByte((totalHeaderSize ~/ 4) - 1);
blockHeader.addByte(0); // flags
blockHeader.add(filterBytes);
for (var i = 0; i < paddingHeader; i++) {
blockHeader.addByte(0);
}
final bhBytes = blockHeader.toBytes();
final bhCrc = getCrc32(bhBytes);
final blockStart = out.length;
out.add(bhBytes);
out.add([bhCrc & 0xff, (bhCrc >> 8) & 0xff, (bhCrc >> 16) & 0xff, (bhCrc >> 24) & 0xff]);
out.add(lzma2Bytes);
final paddingBlock = (4 - (out.length % 4)) % 4;
for (var i = 0; i < paddingBlock; i++) {
out.addByte(0);
}
final unpaddedLength = out.length - blockStart - paddingBlock;
final indexStart = out.length;
final index = BytesBuilder();
index.addByte(0); // indicator
writeLeb128(index, 1);
writeLeb128(index, unpaddedLength);
writeLeb128(index, data.length);
while (index.length % 4 != 0) {
index.addByte(0);
}
final indexBytes = index.toBytes();
final indexCrc = getCrc32(indexBytes);
out.add(indexBytes);
out.add([indexCrc & 0xff, (indexCrc >> 8) & 0xff, (indexCrc >> 16) & 0xff, (indexCrc >> 24) & 0xff]);
final indexTotalSize = out.length - indexStart;
final footer = BytesBuilder();
final indexSizeField = (indexTotalSize ~/ 4) - 1;
footer.add([indexSizeField & 0xff, (indexSizeField >> 8) & 0xff, (indexSizeField >> 16) & 0xff, (indexSizeField >> 24) & 0xff]);
footer.add([0, 0]);
final footerBytes = footer.toBytes();
final footerCrc = getCrc32(footerBytes);
out.add([footerCrc & 0xff, (footerCrc >> 8) & 0xff, (footerCrc >> 16) & 0xff, (footerCrc >> 24) & 0xff]);
out.add(footerBytes);
out.add([89, 90]); // 'YZ'
return out.toBytes();
}
+413
View File
@@ -0,0 +1,413 @@
import 'dart:async';
import 'dart:io';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/distro_manifest.dart';
import 'package:code_editor/providers/distro_provider.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/services/distro_download_manager.dart';
import 'package:code_editor/services/distro_manager.dart';
import 'package:code_editor/views/distro_management_view.dart';
import 'package:code_editor/views/settings_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory tempBaseDir;
late DistroManager manager;
late DistroProvider distroProvider;
late DistroDownloadManager downloadManager;
late SettingsProvider settingsProvider;
setUp(() {
SharedPreferences.setMockInitialValues({});
tempBaseDir = Directory.systemTemp.createTempSync('distro_mgmt_test_');
manager = DistroManager();
manager.customBaseDir = tempBaseDir;
distroProvider = DistroProvider();
settingsProvider = SettingsProvider();
downloadManager = DistroDownloadManager();
downloadManager.customPackagesDir = tempBaseDir;
});
tearDown(() {
manager.customBaseDir = null;
downloadManager.customPackagesDir = null;
if (tempBaseDir.existsSync()) {
tempBaseDir.deleteSync(recursive: true);
}
});
Widget buildTestableWidget({
required Widget child,
Locale locale = const Locale('zh'),
}) {
return MultiProvider(
providers: [
ChangeNotifierProvider<SettingsProvider>.value(value: settingsProvider),
ChangeNotifierProvider<DistroProvider>.value(value: distroProvider),
ChangeNotifierProvider<TerminalProvider>(create: (_) => TerminalProvider()),
],
child: MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale('zh'),
Locale('en'),
],
locale: locale,
home: child,
),
);
}
group('DistroManifest & Repository Tests', () {
test('currentArchDistros only returns systems supported by current arch', () {
final items = DistroRepository.currentArchDistros;
expect(items, isNotEmpty);
// 验证每个条目在当前架构下都有有效的包源
for (final item in items) {
expect(item.currentPackageSource, isNotNull);
expect(item.currentPackageSource!.isNotEmpty, isTrue);
}
// 验证内置系统的 isBuiltin 标识
final ubuntu = items.firstWhere((e) => e.id == 'ubuntu');
expect(ubuntu.isBuiltin, isTrue);
expect(ubuntu.isRecommended, isTrue);
final alpine = items.firstWhere((e) => e.id == 'alpine');
expect(alpine.isBuiltin, isTrue);
});
test('currentArch returns arm64 or x86_64 correctly', () {
final arch = DistroManifestItem.currentArch;
expect(arch == DistroArch.arm64 || arch == DistroArch.x86_64, isTrue);
});
});
group('DistroDownloadManager Tests', () {
test('initial state has no active downloads', () {
final dm = DistroDownloadManager();
expect(dm.isDownloading('unknown_distro'), isFalse);
expect(dm.getProgress('unknown_distro'), isNull);
});
test('package file detection and deletion', () async {
final dm = DistroDownloadManager();
const distroId = 'debian';
const fakeUrl = 'https://example.com/debian.tar.xz';
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isFalse);
final file = await dm.getPackageFile(distroId, fakeUrl);
file.writeAsStringSync('fake tar data');
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isTrue);
await dm.deletePackage(distroId, fakeUrl);
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isFalse);
});
test('cancelDownload immediately stops background streaming, closes file sinks, and cleans up .part file', () async {
await HttpOverrides.runWithHttpOverrides(() async {
final dm = DistroDownloadManager();
const distroId = 'test_cancel_distro';
// 启动一个本地 HTTP 服务器模拟网络流式下载
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final serverUrl = 'http://${server.address.address}:${server.port}/test_image.tar.xz';
final serverCompleter = Completer<void>();
server.listen((HttpRequest request) async {
request.response.bufferOutput = false;
request.response.statusCode = HttpStatus.ok;
request.response.contentLength = 1000000;
request.response.add(List.filled(1024, 42));
await request.response.flush();
// 挂起等待客户端取消
await serverCompleter.future;
try {
await request.response.close();
} catch (_) {}
});
final downloadFuture = dm.startDownload(
distroId: distroId,
downloadUrl: serverUrl,
);
while ((dm.getProgress(distroId)?.receivedBytes ?? 0) == 0) {
await Future.delayed(const Duration(milliseconds: 10));
}
expect(dm.isDownloading(distroId), isTrue);
final partFile = File(p.join(tempBaseDir.path, '${distroId}_rootfs.tar.xz.part'));
expect(partFile.existsSync(), isTrue);
await dm.cancelDownload(distroId);
// 验证取消后:
// 1. isDownloading 为 false
expect(dm.isDownloading(distroId), isFalse);
// 2. 进度映射已被重置清理
expect(dm.getProgress(distroId), isNull);
// 3. .part 临时文件被立即安全删除(Windows 上句柄已完全释放)
expect(partFile.existsSync(), isFalse);
// 唤醒服务端
if (!serverCompleter.isCompleted) {
serverCompleter.complete();
}
// 等待 startDownload Future 完成,并验证返回值必须为 null 且未生成最终文件
final resultFile = await downloadFuture;
expect(resultFile, isNull);
final finalFile = File(p.join(tempBaseDir.path, '${distroId}_rootfs.tar.xz'));
expect(finalFile.existsSync(), isFalse);
await server.close(force: true);
}, _TestHttpOverrides());
});
test('re-download after cancellation succeeds cleanly', () async {
await HttpOverrides.runWithHttpOverrides(() async {
final dm = DistroDownloadManager();
const distroId = 'test_redownload_distro';
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final serverUrl = 'http://${server.address.address}:${server.port}/test_image.tar.xz';
server.listen((HttpRequest request) async {
request.response.statusCode = HttpStatus.ok;
request.response.contentLength = 50;
request.response.add(List.filled(50, 99));
await request.response.close();
});
// 下载能成功完成
final resultFile = await dm.startDownload(
distroId: distroId,
downloadUrl: serverUrl,
);
expect(resultFile, isNotNull);
expect(resultFile!.existsSync(), isTrue);
expect(resultFile.lengthSync(), 50);
expect(dm.getProgress(distroId)?.state, DistroDownloadState.completed);
await server.close(force: true);
}, _TestHttpOverrides());
});
test('startDownload refuses duplicate download and returns existing file when package already exists', () async {
final dm = DistroDownloadManager();
const distroId = 'test_existing_distro';
const fakeUrl = 'https://example.com/test_image.tar.xz';
final file = await dm.getPackageFile(distroId, fakeUrl);
file.writeAsStringSync('existing package content');
expect(await dm.isPackageDownloaded(distroId, fakeUrl), isTrue);
// 再次调用 startDownload,应立即返回已有文件,且不发起网络请求
final returnedFile = await dm.startDownload(
distroId: distroId,
downloadUrl: fakeUrl,
);
expect(returnedFile, isNotNull);
expect(returnedFile!.path, file.path);
expect(dm.getProgress(distroId)?.state, DistroDownloadState.completed);
expect(returnedFile.readAsStringSync(), 'existing package content');
});
});
group('DistroManagementView Requirements Tests', () {
testWidgets('1. 内置字样完全移除,2. 安装按钮和已安装文本去掉', (tester) async {
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
await tester.pumpAndSettle();
// 验证返回按键与标题
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
expect(find.text('系统管理'), findsOneWidget);
// 验证品牌图标存在
expect(find.byType(Image), findsWidgets);
// 1. 验证“内置”字样完全不存在
expect(find.text('内置'), findsNothing);
expect(find.text('Built-in'), findsNothing);
// 2. 验证“安装”按键与“已安装”文本完全不存在
expect(find.text('安装'), findsNothing);
expect(find.text('Install'), findsNothing);
expect(find.text('已安装'), findsNothing);
expect(find.text('Installed'), findsNothing);
// 3. 验证推荐标签保留
expect(find.text('推荐'), findsWidgets);
});
testWidgets('3. 选中后无高亮边框 (border 无突出 primary 高亮)', (tester) async {
// 预置默认选中 ubuntu
await distroProvider.refreshSystems();
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
await tester.pumpAndSettle();
// 获取第一个 Card
final cardFinder = find.byType(Card).first;
final cardWidget = tester.widget<Card>(cardFinder);
final shape = cardWidget.shape as RoundedRectangleBorder;
final side = shape.side;
// 边框宽度为普通 1.0,颜色不是 primary 高亮
expect(side.width, 1.0);
});
testWidgets('4. 内置系统 (ubuntu / alpine) 无法删除,右侧无按键', (tester) async {
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
await tester.pumpAndSettle();
// 在初始未下载任何外部系统的状态下,内置系统右侧没有任何删除按键
expect(find.byIcon(Icons.delete_outline), findsNothing);
});
testWidgets('4. 点击已就绪的 item 本身直接返回 DistroManifestItem', (tester) async {
DistroManifestItem? selectedItem;
await tester.pumpWidget(buildTestableWidget(
child: Builder(
builder: (context) => ElevatedButton(
onPressed: () async {
selectedItem = await Navigator.of(context).push<DistroManifestItem>(
MaterialPageRoute(builder: (_) => const DistroManagementView()),
);
},
child: const Text('Open'),
),
),
));
await tester.pumpAndSettle();
// 打开页面
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
// 点击已就绪的 Alpine Linux 条目本身
await tester.tap(find.text('Alpine Linux'));
await tester.pumpAndSettle();
// 确认返回了 DistroManifestItem
expect(selectedItem, isNotNull);
expect(selectedItem!.id, 'alpine');
});
testWidgets('4. 下载完成的系统右侧显示红色删除按钮,点击弹出删除安装包确认框', (tester) async {
// 模拟 debian 安装包已存在于本地目录
final debianFile = File(p.join(tempBaseDir.path, 'debian_rootfs.tar.xz'));
debianFile.writeAsStringSync('dummy content');
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
await tester.pumpAndSettle();
// debian 应出现红色删除按钮
final deleteBtn = find.byIcon(Icons.delete_outline);
expect(deleteBtn, findsOneWidget);
// 点击删除按钮弹出“确认删除安装包”对话框
await tester.tap(deleteBtn);
await tester.pumpAndSettle();
expect(find.text('确认删除安装包'), findsOneWidget);
});
testWidgets('下载完成后页面立即响应更新为就绪状态,无需退出重新进入', (tester) async {
await tester.pumpWidget(buildTestableWidget(child: const DistroManagementView()));
await tester.pumpAndSettle();
// 此时 debian 处于未下载状态,显示“下载”按钮
expect(find.text('下载'), findsWidgets);
// 模拟下载管理器写入完成包
final debianFile = await downloadManager.getPackageFile('debian', 'https://example.com/debian.tar.xz');
debianFile.writeAsStringSync('debian package content');
// 触发 startDownload,由于本地文件已完备,会直接更新状态并通知监听器
await downloadManager.startDownload(distroId: 'debian', downloadUrl: 'https://example.com/debian.tar.xz');
await tester.pumpAndSettle();
// debian 的卡片立即就绪,出现红色删除按钮
expect(find.byIcon(Icons.delete_outline), findsOneWidget);
});
});
group('SettingsView Download Mirror Tests', () {
testWidgets('设置页面项目下方展示“下载”分组,默认显示清华源', (tester) async {
await tester.pumpWidget(buildTestableWidget(child: const SettingsView()));
await tester.pumpAndSettle();
// 滚动到“下载”分组可见
await tester.scrollUntilVisible(
find.text('下载'),
300,
scrollable: find.byType(Scrollable).first,
);
await tester.pumpAndSettle();
// 验证“下载”分组标题与“下载源”
expect(find.text('下载'), findsOneWidget);
expect(find.text('下载源'), findsOneWidget);
expect(find.text('清华大学开源软件镜像站 (推荐)'), findsOneWidget);
});
testWidgets('点击下载源弹出底部选择菜单,可自由切换至北外源', (tester) async {
await tester.pumpWidget(buildTestableWidget(child: const SettingsView()));
await tester.pumpAndSettle();
// 滚动到“下载源”可见
await tester.scrollUntilVisible(
find.text('下载源'),
300,
scrollable: find.byType(Scrollable).first,
);
await tester.pumpAndSettle();
// 点击下载源条目弹出 BottomSheet
await tester.tap(find.text('下载源'));
await tester.pumpAndSettle();
expect(find.text('选择下载源'), findsOneWidget);
expect(find.text('北京外国语大学开源软件镜像站'), findsOneWidget);
expect(find.text('中国科学院软件研究所开源镜像站'), findsOneWidget);
expect(find.text('LinuxContainers 官方镜像源'), findsOneWidget);
// 选中北外源
await tester.tap(find.text('北京外国语大学开源软件镜像站'));
await tester.pumpAndSettle();
// 验证 SettingsProvider 状态更新
expect(settingsProvider.downloadMirrorId, 'bfsu');
expect(find.text('北京外国语大学开源软件镜像站'), findsOneWidget);
});
});
}
class _TestHttpOverrides extends HttpOverrides {}
+175
View File
@@ -7,12 +7,47 @@ import 'package:code_editor/providers/terminal_provider.dart';
import 'package:code_editor/services/distro_installer.dart';
import 'package:code_editor/services/distro_manager.dart';
import 'package:code_editor/widgets/distro_selector_dialog.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MockDistroFilePicker extends FilePicker {
String? pickedPath;
@override
Future<FilePickerResult?> pickFiles({
String? dialogTitle,
String? initialDirectory,
FileType type = FileType.any,
List<String>? allowedExtensions,
Function(FilePickerStatus)? onFileLoading,
bool allowCompression = false,
int compressionQuality = 30,
bool allowMultiple = false,
bool withData = false,
bool withReadStream = false,
bool lockParentWindow = false,
bool readSequential = false,
}) async {
if (pickedPath == null) return null;
return FilePickerResult([
PlatformFile(name: p.basename(pickedPath!), size: 10, path: pickedPath),
]);
}
@override
Future<bool?> clearTemporaryFiles() async => true;
@override
Future<String?> getDirectoryPath({String? dialogTitle, bool lockParentWindow = false, String? initialDirectory}) async => null;
@override
Future<String?> saveFile({String? dialogTitle, String? fileName, String? initialDirectory, FileType type = FileType.any, List<String>? allowedExtensions, Uint8List? bytes, bool lockParentWindow = false}) async => null;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@@ -171,6 +206,92 @@ void main() {
expect(launchConfig.arguments, contains('-k'));
expect(launchConfig.arguments, contains('5.4.0-proot'));
expect(launchConfig.environment['PROOT_L2S_DIR'], isNotNull);
expect(launchConfig.environment['SHELL'], equals('/bin/sh'));
expect(launchConfig.arguments, contains('SHELL=/bin/sh'));
expect(launchConfig.arguments, contains('-l'));
expect(launchConfig.arguments, contains('-i'));
});
test('buildLaunchConfig 自动检测 rootfs 中的 /bin/bash 并设置为交互式登录 Shell', () async {
final gzBytes = createMockRootfsTarGz();
final tempGzFile = File(p.join(tempBaseDir.path, 'bash_cfg.tar.gz'))..writeAsBytesSync(gzBytes);
await manager.importFromCustomTarGz(systemName: 'ubuntu_env', tarGzFile: tempGzFile);
final rootDir = await manager.getSystemRootDir('ubuntu_env');
// 模拟 Ubuntu 根文件系统中自带的 bash
final bashFile = File(p.join(rootDir.path, 'bin', 'bash'));
await bashFile.create(recursive: true);
final launchConfig = await manager.buildLaunchConfig(
systemName: 'ubuntu_env',
workspacePath: tempBaseDir.path,
);
expect(launchConfig.environment['SHELL'], equals('/bin/bash'));
expect(launchConfig.arguments, contains('SHELL=/bin/bash'));
expect(launchConfig.arguments, contains('/bin/bash'));
expect(launchConfig.arguments, contains('-l'));
expect(launchConfig.arguments, contains('-i'));
// 验证 Android 宿主特权/辅助组自动写入 /etc/group 与 .hushlogin 生成
final groupFile = File(p.join(rootDir.path, 'etc', 'group'));
expect(groupFile.existsSync(), isTrue);
final groupContent = groupFile.readAsStringSync();
expect(groupContent, contains('aid_inet:x:3003:'));
expect(groupContent, contains('aid_ext_data_rw:x:1077:'));
expect(groupContent, contains('aid_everybody:x:9997:'));
final hushFile = File(p.join(rootDir.path, 'root', '.hushlogin'));
expect(hushFile.existsSync(), isTrue);
});
test('buildLaunchConfig 针对不同发行版(Alpine ash vs passwd 自定义 shell)自适应启动参数', () async {
final gzBytes = createMockRootfsTarGz();
final tempGzFile = File(p.join(tempBaseDir.path, 'alpine_cfg.tar.gz'))..writeAsBytesSync(gzBytes);
await manager.importFromCustomTarGz(systemName: 'alpine_env', tarGzFile: tempGzFile);
final rootDir = await manager.getSystemRootDir('alpine_env');
// 1. 模拟 Alpine(无 bash,自带 ash,/etc/passwd 中 root 为 /bin/ash)
final ashFile = File(p.join(rootDir.path, 'bin', 'ash'));
await ashFile.create(recursive: true);
final passwdFile = File(p.join(rootDir.path, 'etc', 'passwd'));
await passwdFile.writeAsString('root:x:0:0:root:/root:/bin/ash\n');
final alpineConfig = await manager.buildLaunchConfig(
systemName: 'alpine_env',
workspacePath: tempBaseDir.path,
);
expect(alpineConfig.environment['SHELL'], equals('/bin/ash'));
expect(alpineConfig.arguments, contains('/bin/ash'));
expect(alpineConfig.arguments, contains('-l'));
expect(alpineConfig.arguments, contains('-i'));
// 2. 模拟用户安装并切换为 /bin/zsh
final zshFile = File(p.join(rootDir.path, 'bin', 'zsh'));
await zshFile.create(recursive: true);
await passwdFile.writeAsString('root:x:0:0:root:/root:/bin/zsh\n');
final zshConfig = await manager.buildLaunchConfig(
systemName: 'alpine_env',
workspacePath: tempBaseDir.path,
);
expect(zshConfig.environment['SHELL'], equals('/bin/zsh'));
expect(zshConfig.arguments, contains('/bin/zsh'));
expect(zshConfig.arguments, contains('-l'));
expect(zshConfig.arguments, contains('-i'));
});
test('buildLaunchConfig 在 host 模式下正确配置 SHELL 与 -i 交互模式', () async {
final hostConfig = await manager.buildLaunchConfig(
systemName: 'host',
workspacePath: tempBaseDir.path,
);
expect(hostConfig.executable, equals('/system/bin/sh'));
expect(hostConfig.arguments, contains('-i'));
expect(hostConfig.environment['SHELL'], equals('/system/bin/sh'));
});
});
@@ -294,5 +415,59 @@ void main() {
// 验证存在高危删除按钮
expect(find.byIcon(Icons.delete_outline), findsOneWidget);
});
testWidgets('DistroSelectorDialog 导入外部系统选择不支持的格式时显示错误 Toast 并中止流程', (tester) async {
final mockPicker = MockDistroFilePicker();
FilePicker.platform = mockPicker;
// 设置选中的文件为不受支持的格式(如 .zip 或 .txt)
final unsupportedFile = File(p.join(tempBaseDir.path, 'rootfs_image.zip'))..writeAsStringSync('zip content');
mockPicker.pickedPath = unsupportedFile.path;
final distroProvider = DistroProvider();
await tester.runAsync(() async {
await distroProvider.init();
});
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<DistroProvider>.value(value: distroProvider),
ChangeNotifierProvider<TerminalProvider>(create: (_) => TerminalProvider()),
],
child: MaterialApp(
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const Scaffold(
body: DistroSelectorDialog(),
),
),
),
);
await tester.pumpAndSettle();
// 点击导入按钮打开 PopupMenu
final importButton = find.byIcon(Icons.add_circle_outline);
expect(importButton, findsOneWidget);
await tester.tap(importButton);
await tester.pumpAndSettle();
// 点击“从外部导入 (.tar.gz)”
final externalItem = find.text('从外部导入 (.tar.gz)');
expect(externalItem, findsOneWidget);
await tester.tap(externalItem);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
// 验证不应弹出系统名称输入弹窗
expect(find.text('导入外部系统'), findsNothing);
// 验证弹出指定格式错误 Toast
expect(find.text('不支持的文件格式,仅支持系统镜像包 (.tar.gz, .tar.xz, .tar)'), findsOneWidget);
// 等待 Toast 定时器安全结束
await tester.pump(const Duration(seconds: 3));
});
});
}
+145
View File
@@ -0,0 +1,145 @@
import 'dart:io';
import 'package:archive/archive_io.dart';
import 'package:code_editor/services/internal_project_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory tempBaseDir;
late InternalProjectService service;
setUp(() {
tempBaseDir = Directory.systemTemp.createTempSync('internal_project_test_');
service = InternalProjectService.instance;
service.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects'));
});
tearDown(() {
service.customProjectsDir = null;
if (tempBaseDir.existsSync()) {
tempBaseDir.deleteSync(recursive: true);
}
});
group('InternalProjectService Unit Tests', () {
test('getProjectsDirectory creates directory if it does not exist', () async {
final dir = await service.getProjectsDirectory();
expect(dir.existsSync(), isTrue);
expect(p.split(dir.path), containsAll(['files', 'projects']));
});
test('createProject successfully creates new project folder', () async {
final projectDir = await service.createProject('my_cool_project');
expect(projectDir.existsSync(), isTrue);
expect(p.basename(projectDir.path), 'my_cool_project');
final exists = await service.projectExists('my_cool_project');
expect(exists, isTrue);
});
test('createProject throws when name is empty or already exists', () async {
expect(() => service.createProject(' '), throwsA(isA<FileSystemException>()));
await service.createProject('unique_project');
expect(() => service.createProject('unique_project'), throwsA(isA<FileSystemException>()));
});
test('listProjects returns sorted directories', () async {
await service.createProject('project_c');
await service.createProject('project_a');
await service.createProject('project_b');
final list = await service.listProjects();
expect(list.length, 3);
expect(p.basename(list[0].path), 'project_a');
expect(p.basename(list[1].path), 'project_b');
expect(p.basename(list[2].path), 'project_c');
});
test('renameProject successfully renames project folder', () async {
final original = await service.createProject('old_name');
expect(original.existsSync(), isTrue);
final renamed = await service.renameProject(original, 'new_name');
expect(original.existsSync(), isFalse);
expect(renamed.existsSync(), isTrue);
expect(p.basename(renamed.path), 'new_name');
final list = await service.listProjects();
expect(list.length, 1);
expect(p.basename(list[0].path), 'new_name');
});
test('renameProject throws if target name already exists or is empty', () async {
final p1 = await service.createProject('p1');
await service.createProject('p2');
expect(() => service.renameProject(p1, ' '), throwsA(isA<FileSystemException>()));
expect(() => service.renameProject(p1, 'p2'), throwsA(isA<FileSystemException>()));
});
test('deleteProject recursively deletes project folder', () async {
final projectDir = await service.createProject('to_delete');
// Create subfile inside project
final subFile = File(p.join(projectDir.path, 'main.dart'));
await subFile.writeAsString('void main() {}');
expect(subFile.existsSync(), isTrue);
await service.deleteProject(projectDir);
expect(projectDir.existsSync(), isFalse);
expect(await service.projectExists('to_delete'), isFalse);
});
test('isInternalProject correctly identifies internal vs external paths', () async {
final proj = await service.createProject('my_app');
expect(service.isInternalProject(proj.path), isTrue);
expect(service.isInternalProject(null), isFalse);
expect(service.isInternalProject(''), isFalse);
expect(service.isInternalProject(' '), isFalse);
expect(service.isInternalProject('C:/Users/SomeUser/Desktop/other_project'), isFalse);
expect(service.isInternalProject('/storage/emulated/0/Download/some_proj'), isFalse);
});
test('importProjectFromArchive extracts archive into new project directory', () async {
// Create a test zip file
final zipFilePath = p.join(tempBaseDir.path, 'sample_project.zip');
final encoder = ZipFileEncoder();
encoder.create(zipFilePath);
final dummyFile = File(p.join(tempBaseDir.path, 'readme.md'));
dummyFile.writeAsStringSync('# Test Project');
encoder.addFile(dummyFile);
encoder.close();
final importedDir = await service.importProjectFromArchive(zipFilePath, 'sample_project');
expect(importedDir.existsSync(), isTrue);
expect(p.basename(importedDir.path), 'sample_project');
final extractedReadme = File(p.join(importedDir.path, 'readme.md'));
expect(extractedReadme.existsSync(), isTrue);
expect(extractedReadme.readAsStringSync(), '# Test Project');
// Verify listing includes imported project
final list = await service.listProjects();
expect(list.any((d) => p.basename(d.path) == 'sample_project'), isTrue);
});
test('importProjectFromArchive throws when target project already exists or archive missing', () async {
await service.createProject('existing_project');
final zipFilePath = p.join(tempBaseDir.path, 'dummy.zip');
expect(
() => service.importProjectFromArchive(zipFilePath, 'existing_project'),
throwsA(isA<FileSystemException>()),
);
expect(
() => service.importProjectFromArchive(zipFilePath, 'non_existent_zip_proj'),
throwsA(isA<FileSystemException>()),
);
});
});
}
+533
View File
@@ -0,0 +1,533 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:archive/archive_io.dart';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/project_history.dart';
import 'package:code_editor/providers/project_provider.dart';
import 'package:code_editor/providers/run_provider.dart';
import 'package:code_editor/providers/settings_provider.dart';
import 'package:code_editor/providers/tab_provider.dart';
import 'package:code_editor/services/internal_project_service.dart';
import 'package:code_editor/views/project_management_view.dart';
import 'package:code_editor/widgets/code_editor_drawer.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MockFilePicker extends FilePicker {
String? pickedPath;
@override
Future<FilePickerResult?> pickFiles({
String? dialogTitle,
String? initialDirectory,
FileType type = FileType.any,
List<String>? allowedExtensions,
Function(FilePickerStatus)? onFileLoading,
bool allowCompression = false,
int compressionQuality = 30,
bool allowMultiple = false,
bool withData = false,
bool withReadStream = false,
bool lockParentWindow = false,
bool readSequential = false,
}) async {
if (pickedPath == null) return null;
return FilePickerResult([
PlatformFile(name: p.basename(pickedPath!), size: 10, path: pickedPath),
]);
}
@override
Future<bool?> clearTemporaryFiles() async => true;
@override
Future<String?> getDirectoryPath({
String? dialogTitle,
bool lockParentWindow = false,
String? initialDirectory,
}) async => null;
@override
Future<String?> saveFile({
String? dialogTitle,
String? fileName,
String? initialDirectory,
FileType type = FileType.any,
List<String>? allowedExtensions,
Uint8List? bytes,
bool lockParentWindow = false,
}) async => null;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory tempBaseDir;
late InternalProjectService projectService;
late ProjectProvider projectProvider;
late TabProvider tabProvider;
late SettingsProvider settingsProvider;
late RunProvider runProvider;
late MockFilePicker mockFilePicker;
setUp(() {
SharedPreferences.setMockInitialValues({});
tempBaseDir = Directory.systemTemp.createTempSync('project_mgmt_widget_test_');
projectService = InternalProjectService.instance;
projectService.customProjectsDir = Directory(p.join(tempBaseDir.path, 'files', 'projects'));
projectProvider = ProjectProvider();
tabProvider = TabProvider()..bindProjectProvider(projectProvider);
settingsProvider = SettingsProvider();
runProvider = RunProvider();
mockFilePicker = MockFilePicker();
FilePicker.platform = mockFilePicker;
});
tearDown(() {
projectService.customProjectsDir = null;
if (tempBaseDir.existsSync()) {
tempBaseDir.deleteSync(recursive: true);
}
});
Widget buildTestWidget({
required Widget child,
Locale locale = const Locale('zh'),
}) {
return MultiProvider(
providers: [
ChangeNotifierProvider<ProjectProvider>.value(value: projectProvider),
ChangeNotifierProvider<TabProvider>.value(value: tabProvider),
ChangeNotifierProvider<SettingsProvider>.value(value: settingsProvider),
ChangeNotifierProvider<RunProvider>.value(value: runProvider),
],
child: MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [
Locale('zh'),
Locale('en'),
],
locale: locale,
home: child,
),
);
}
group('Drawer Open Project Menu Tests', () {
testWidgets('Clicking open project button pops up menu with two options (zh & en)', (tester) async {
await tester.pumpWidget(buildTestWidget(
child: const Scaffold(
drawer: CodeEditorDrawer(),
body: Center(child: Text('Main')),
),
locale: const Locale('zh'),
));
// Open drawer
final scaffoldState = tester.state<ScaffoldState>(find.byType(Scaffold));
scaffoldState.openDrawer();
await tester.pumpAndSettle();
// Find the folder_open popup menu button
final openButton = find.byIcon(Icons.folder_open);
expect(openButton, findsOneWidget);
await tester.tap(openButton);
await tester.pumpAndSettle();
// Check popup menu items
expect(find.text('从软件内打开'), findsOneWidget);
expect(find.text('从外部打开'), findsOneWidget);
});
testWidgets('Clicking open from app navigates to ProjectManagementView', (tester) async {
await tester.pumpWidget(buildTestWidget(
child: const Scaffold(
drawer: CodeEditorDrawer(),
body: Center(child: Text('Main')),
),
));
final scaffoldState = tester.state<ScaffoldState>(find.byType(Scaffold));
scaffoldState.openDrawer();
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.folder_open));
await tester.pumpAndSettle();
await tester.tap(find.text('从软件内打开'));
await tester.pumpAndSettle();
// Should now be on ProjectManagementView
expect(find.byType(ProjectManagementView), findsOneWidget);
expect(find.text('项目'), findsOneWidget);
expect(find.byTooltip('新建项目'), findsOneWidget);
expect(find.byTooltip('从外部导入'), findsOneWidget);
});
testWidgets('Drawer header subtitle shows project name for internal projects, root path for external projects', (tester) async {
final internalProj = await projectService.createProject('my_internal_app');
// 1. 设置内部项目
projectProvider.setHistoryForTesting(ProjectHistory(
rootPath: internalProj.path,
lastOpenedFilePath: null,
));
await tester.pumpWidget(buildTestWidget(
child: const Scaffold(
drawer: CodeEditorDrawer(),
body: Center(child: Text('Main')),
),
));
final scaffoldState = tester.state<ScaffoldState>(find.byType(Scaffold));
scaffoldState.openDrawer();
await tester.pumpAndSettle();
// 内部项目应当只显示项目名称,而非完整根路径
expect(find.text('my_internal_app'), findsOneWidget);
expect(find.text(internalProj.path), findsNothing);
// 2. 切换为外部项目
final externalPath = p.normalize('C:/outside/external_project');
projectProvider.setHistoryForTesting(ProjectHistory(
rootPath: externalPath,
lastOpenedFilePath: null,
));
await tester.pumpAndSettle();
// 外部项目应显示完整根路径
expect(find.text(externalPath), findsOneWidget);
});
});
group('ProjectManagementView Feature Tests', () {
testWidgets('Empty state displays placeholder icon and text', (tester) async {
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
expect(find.text('暂无项目,点击右上角新建项目'), findsOneWidget);
expect(find.byIcon(Icons.folder_open_outlined), findsOneWidget);
expect(find.text('项目'), findsOneWidget);
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
expect(find.byIcon(Icons.file_upload_outlined), findsOneWidget);
expect(find.byTooltip('从外部导入'), findsOneWidget);
expect(find.byIcon(Icons.add), findsOneWidget);
expect(find.byTooltip('新建项目'), findsOneWidget);
});
testWidgets('Creating a new project via dialog adds item to the list', (tester) async {
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
// Tap "新建项目" button (IconButton with tooltip '新建项目')
await tester.tap(find.byTooltip('新建项目'));
await tester.pumpAndSettle();
// Dialog should appear
expect(find.text('请输入项目名称'), findsOneWidget);
// Enter project name
await tester.enterText(find.byType(TextFormField), 'my_flutter_app');
await tester.pumpAndSettle();
// Tap confirm button ("确定")
await tester.tap(find.text('确定'));
await tester.pump();
await tester.pump(const Duration(seconds: 3));
// Project item should now exist in list
expect(find.text('my_flutter_app'), findsOneWidget);
expect(find.byIcon(Icons.edit_outlined), findsOneWidget);
expect(find.byIcon(Icons.delete_outline), findsOneWidget);
// Verify directory was actually created
final projects = await projectService.listProjects();
expect(projects.length, 1);
expect(p.basename(projects.first.path), 'my_flutter_app');
});
testWidgets('Renaming a project updates folder and UI', (tester) async {
await projectService.createProject('initial_proj');
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
expect(find.text('initial_proj'), findsOneWidget);
// Tap edit button
await tester.tap(find.byIcon(Icons.edit_outlined));
await tester.pumpAndSettle();
// Dialog should appear with 'initial_proj'
expect(find.text('重命名项目'), findsOneWidget);
expect(find.text('initial_proj'), findsWidgets);
// Enter new name
await tester.enterText(find.byType(TextFormField), 'renamed_proj');
await tester.pumpAndSettle();
await tester.tap(find.text('确定'));
await tester.pump();
await tester.pump(const Duration(seconds: 3));
// Check UI updated
expect(find.text('renamed_proj'), findsOneWidget);
expect(find.text('initial_proj'), findsNothing);
// Verify on disk
final projects = await projectService.listProjects();
expect(projects.length, 1);
expect(p.basename(projects.first.path), 'renamed_proj');
});
testWidgets('Deleting a project pops confirmation dialog and deletes folder on confirm', (tester) async {
await projectService.createProject('project_to_remove');
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
expect(find.text('project_to_remove'), findsOneWidget);
// Tap delete button
await tester.tap(find.byIcon(Icons.delete_outline));
await tester.pumpAndSettle();
// Confirmation dialog should appear
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('删除项目'), findsOneWidget);
expect(find.text('确定要删除项目 "project_to_remove" 吗?此操作不可逆。'), findsOneWidget);
// Tap cancel first
await tester.tap(find.text('取消'));
await tester.pumpAndSettle();
// Item should still be there
expect(find.text('project_to_remove'), findsOneWidget);
// Tap delete again and confirm
await tester.tap(find.byIcon(Icons.delete_outline));
await tester.pumpAndSettle();
await tester.tap(find.text('删除'));
await tester.pump();
await tester.pump(const Duration(seconds: 3));
// Should now be empty
expect(find.text('project_to_remove'), findsNothing);
expect(find.text('暂无项目,点击右上角新建项目'), findsOneWidget);
// Verify on disk
final projects = await projectService.listProjects();
expect(projects, isEmpty);
});
testWidgets('Tapping project item opens project and returns to main view', (tester) async {
final projDir = await projectService.createProject('opened_project');
// Create a dummy file in the project
File(p.join(projDir.path, 'hello.txt')).writeAsStringSync('world');
await tester.pumpWidget(buildTestWidget(
child: Builder(
builder: (context) => Scaffold(
body: ElevatedButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const ProjectManagementView()),
),
child: const Text('Go to PM'),
),
),
),
));
// Navigate to ProjectManagementView
await tester.tap(find.text('Go to PM'));
await tester.pumpAndSettle();
expect(find.byType(ProjectManagementView), findsOneWidget);
expect(find.text('opened_project'), findsOneWidget);
// Tap the project item inside runAsync so FileService buildTree stream can complete
await tester.runAsync(() async {
await tester.tap(find.text('opened_project'));
await Future.delayed(const Duration(milliseconds: 200));
});
await tester.pumpAndSettle();
// Should have popped back to previous view
expect(find.byType(ProjectManagementView), findsNothing);
expect(find.text('Go to PM'), findsOneWidget);
// Verify ProjectProvider opened the project
expect(projectProvider.rootPath, p.normalize(projDir.path));
});
testWidgets('Full English locale validation (no hardcoded Chinese)', (tester) async {
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
locale: const Locale('en'),
));
await tester.pumpAndSettle();
// English texts in AppBar and empty state
expect(find.text('Projects'), findsOneWidget);
expect(find.byTooltip('New Project'), findsOneWidget);
expect(find.byTooltip('Import from External'), findsOneWidget);
expect(find.text('No projects yet, click top right to create one'), findsOneWidget);
// Tap New Project
await tester.tap(find.byTooltip('New Project'));
await tester.pumpAndSettle();
expect(find.text('Enter project name'), findsOneWidget);
expect(find.text('Cancel'), findsOneWidget);
expect(find.text('Confirm'), findsOneWidget);
});
testWidgets('Importing project from external archive prompts for name and extracts upon confirmation', (tester) async {
// Create a test zip
final zipFilePath = p.join(tempBaseDir.path, 'imported_pkg.zip');
final encoder = ZipFileEncoder();
encoder.create(zipFilePath);
final dummyFile = File(p.join(tempBaseDir.path, 'info.txt'));
dummyFile.writeAsStringSync('package contents');
encoder.addFile(dummyFile);
encoder.close();
mockFilePicker.pickedPath = zipFilePath;
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
// Tap import button
await tester.tap(find.byTooltip('从外部导入'));
await tester.pumpAndSettle();
// Dialog should appear with default name from filename "imported_pkg"
expect(find.text('确认项目名称'), findsOneWidget);
expect(find.text('imported_pkg'), findsOneWidget);
// Confirm project name inside runAsync so extractFileToDisk file streams can complete
await tester.runAsync(() async {
await tester.tap(find.text('确定'));
await tester.pump();
for (int i = 0; i < 20; i++) {
await Future.delayed(const Duration(milliseconds: 100));
if (await projectService.projectExists('imported_pkg')) {
break;
}
}
});
await tester.pump();
await tester.pump(const Duration(seconds: 3));
// Should now show in list
expect(find.text('imported_pkg'), findsOneWidget);
// Verify directory on disk
final projects = await projectService.listProjects();
expect(projects.length, 1);
expect(p.basename(projects.first.path), 'imported_pkg');
expect(File(p.join(projects.first.path, 'info.txt')).existsSync(), isTrue);
});
testWidgets('Canceling import dialog does not import or create project', (tester) async {
final zipFilePath = p.join(tempBaseDir.path, 'cancel_test.zip');
final encoder = ZipFileEncoder();
encoder.create(zipFilePath);
encoder.close();
mockFilePicker.pickedPath = zipFilePath;
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('从外部导入'));
await tester.pumpAndSettle();
expect(find.text('确认项目名称'), findsOneWidget);
// Tap Cancel
await tester.tap(find.text('取消'));
await tester.pumpAndSettle();
// No projects created
expect(find.text('cancel_test'), findsNothing);
expect(find.text('暂无项目,点击右上角新建项目'), findsOneWidget);
final projects = await projectService.listProjects();
expect(projects, isEmpty);
});
testWidgets('Project items do not have Divider separators', (tester) async {
await projectService.createProject('project_1');
await projectService.createProject('project_2');
await projectService.createProject('project_3');
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
expect(find.text('project_1'), findsOneWidget);
expect(find.text('project_2'), findsOneWidget);
expect(find.text('project_3'), findsOneWidget);
// Verify no Divider widgets exist between items
expect(find.byType(Divider), findsNothing);
});
testWidgets('Selecting unsupported file format shows error toast and aborts import', (tester) async {
final invalidFile = File(p.join(tempBaseDir.path, 'unsupported.pdf'));
invalidFile.writeAsStringSync('not an archive');
mockFilePicker.pickedPath = invalidFile.path;
await tester.pumpWidget(buildTestWidget(
child: const ProjectManagementView(),
));
await tester.pumpAndSettle();
// Tap import button
await tester.tap(find.byTooltip('从外部导入'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
// Confirmation dialog should NOT appear
expect(find.text('确认项目名称'), findsNothing);
// Error toast should appear
expect(find.text('不支持的文件格式,仅支持压缩包格式 (.zip, .tar.gz, .tar.xz, .tar 等)'), findsOneWidget);
// Wait for toast to dismiss
await tester.pump(const Duration(seconds: 3));
// Verify no project created
final projects = await projectService.listProjects();
expect(projects, isEmpty);
});
});
}
+330
View File
@@ -1,8 +1,13 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:code_editor/l10n/app_localizations.dart';
import 'package:code_editor/models/run_task.dart';
import 'package:code_editor/providers/run_provider.dart';
import 'package:code_editor/services/run_task_storage_service.dart';
import 'package:code_editor/services/project_task_detector.dart';
import 'package:code_editor/widgets/run_tasks_dialog.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@@ -78,5 +83,330 @@ void main() {
expect(tasks.any((t) => t.id == 'detected_cmake_build_run'), isTrue);
expect(tasks.any((t) => t.id == 'detected_cmake_clean'), isTrue);
});
test('ProjectTaskDetector detects Makefile, Gradle, Cargo, NPM, Dart and source files', () async {
final makefile = File('${tempDir.path}/Makefile');
await makefile.writeAsString('all:\n\tgcc main.c\n');
final cargoToml = File('${tempDir.path}/Cargo.toml');
await cargoToml.writeAsString('[package]\nname = "demo"\n');
final packageJson = File('${tempDir.path}/package.json');
await packageJson.writeAsString('{"name": "demo"}');
final pubspec = File('${tempDir.path}/pubspec.yaml');
await pubspec.writeAsString('name: demo\n');
final gradlew = File('${tempDir.path}/gradlew');
await gradlew.writeAsString('#!/bin/sh\n');
final cppFile = File('${tempDir.path}/main.cpp');
await cppFile.writeAsString('int main() { return 0; }');
final tasks = await ProjectTaskDetector.detect(
projectRoot: tempDir.path,
currentFilePath: cppFile.path,
);
expect(tasks.any((t) => t.id == 'detected_single_cpp'), isTrue);
expect(tasks.first.command, contains('g++'));
expect(tasks.any((t) => t.id == 'detected_make_default'), isTrue);
expect(tasks.any((t) => t.id == 'detected_cargo_run'), isTrue);
expect(tasks.any((t) => t.id == 'detected_npm_start'), isTrue);
expect(tasks.any((t) => t.id == 'detected_dart_run'), isTrue);
expect(tasks.any((t) => t.id == 'detected_gradle_run'), isTrue);
});
});
group('RunTask Localization Tests', () {
testWidgets('getLocalizedDescription returns correct localized text in zh and en for all detected tasks', (tester) async {
late AppLocalizations l10nZh;
late AppLocalizations l10nEn;
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('zh'), Locale('en')],
locale: const Locale('zh'),
home: Builder(builder: (ctx) {
l10nZh = AppLocalizations.of(ctx)!;
return const SizedBox();
}),
),
);
await tester.pumpAndSettle();
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('zh'), Locale('en')],
locale: const Locale('en'),
home: Builder(builder: (ctx) {
l10nEn = AppLocalizations.of(ctx)!;
return const SizedBox();
}),
),
);
await tester.pumpAndSettle();
const gradleRunTask = RunTask(
id: 'detected_gradle_run',
name: 'Gradle: Run',
command: 'sh ./gradlew run',
source: TaskSource.detected,
);
expect(gradleRunTask.getLocalizedDescription(l10nZh), '执行应用程序主入口');
expect(gradleRunTask.getLocalizedDescription(l10nEn), 'Execute application main entrypoint');
const gradleAssembleTask = RunTask(
id: 'detected_gradle_assemble',
name: 'Gradle: Assemble Debug',
command: 'sh ./gradlew assembleDebug',
source: TaskSource.detected,
);
expect(gradleAssembleTask.getLocalizedDescription(l10nZh), '构建调试输出包');
expect(gradleAssembleTask.getLocalizedDescription(l10nEn), 'Build debug output package');
const gradleBuildTask = RunTask(
id: 'detected_gradle_build',
name: 'Gradle: Build',
command: 'sh ./gradlew build',
source: TaskSource.detected,
);
expect(gradleBuildTask.getLocalizedDescription(l10nZh), '执行完整构建与测试');
expect(gradleBuildTask.getLocalizedDescription(l10nEn), 'Execute full build and tests');
const cmakeBuildRunTask = RunTask(
id: 'detected_cmake_build_run',
name: 'CMake: Build & Run',
command: 'cmake -B build',
source: TaskSource.detected,
);
expect(cmakeBuildRunTask.getLocalizedDescription(l10nZh), '配置、编译并尝试启动生成的目标程序');
expect(cmakeBuildRunTask.getLocalizedDescription(l10nEn), 'Configure, build, and try launching the target executable');
});
testWidgets('RunTasksDialog displays English descriptions when locale is en', (tester) async {
const detectedTasks = [
RunTask(
id: 'detected_gradle_run',
name: 'Gradle: Run',
command: 'sh ./gradlew run',
source: TaskSource.detected,
),
RunTask(
id: 'detected_gradle_assemble',
name: 'Gradle: Assemble Debug',
command: 'sh ./gradlew assembleDebug',
source: TaskSource.detected,
),
RunTask(
id: 'detected_gradle_build',
name: 'Gradle: Build',
command: 'sh ./gradlew build',
source: TaskSource.detected,
),
];
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('zh'), Locale('en')],
locale: const Locale('en'),
home: Scaffold(
body: RunTasksDialog(
customTasks: const [],
detectedTasks: detectedTasks,
onTaskSelected: (_) {},
onEditCustomTasks: () {},
),
),
),
);
await tester.pumpAndSettle();
// In English, subtitles should be in English
expect(find.text('Execute application main entrypoint'), findsOneWidget);
expect(find.text('Build debug output package'), findsOneWidget);
expect(find.text('Execute full build and tests'), findsOneWidget);
// Chinese text should NOT appear
expect(find.text('执行应用程序主入口'), findsNothing);
expect(find.text('构建调试输出包'), findsNothing);
expect(find.text('执行完整构建与测试'), findsNothing);
});
testWidgets('RunTasksDialog displays Chinese descriptions when locale is zh', (tester) async {
const detectedTasks = [
RunTask(
id: 'detected_gradle_run',
name: 'Gradle: Run',
command: 'sh ./gradlew run',
source: TaskSource.detected,
),
];
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('zh'), Locale('en')],
locale: const Locale('zh'),
home: Scaffold(
body: RunTasksDialog(
customTasks: const [],
detectedTasks: detectedTasks,
onTaskSelected: (_) {},
onEditCustomTasks: () {},
),
),
),
);
await tester.pumpAndSettle();
// In Chinese, subtitles should be in Chinese
expect(find.text('执行应用程序主入口'), findsOneWidget);
expect(find.text('Execute application main entrypoint'), findsNothing);
});
testWidgets('Missing distro dialog renders without overflow in English on narrow screen', (tester) async {
tester.view.physicalSize = const Size(320, 640);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: const [Locale('zh'), Locale('en')],
locale: const Locale('en'),
home: Builder(
builder: (context) {
final l10n = AppLocalizations.of(context)!;
return Scaffold(
body: AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
title: Row(
children: [
const Icon(Icons.warning_amber_rounded, color: Colors.orange, size: 24),
const SizedBox(width: 8),
Expanded(
child: Text(
l10n.missingDistroTitle,
overflow: TextOverflow.ellipsis,
),
),
],
),
content: Text(l10n.noDistroAvailableContent),
actions: [
TextButton(onPressed: () {}, child: Text(l10n.cancel)),
ElevatedButton.icon(
onPressed: () {},
icon: const Icon(Icons.dns_outlined, size: 18),
label: Text(l10n.systemManagement),
),
],
),
);
},
),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('System Environment Not Ready'), findsOneWidget);
expect(find.text('No available Linux execution environment detected.\n\nProject tasks need to run inside a Linux container. Please install or download a Linux system first (e.g. Ubuntu or Alpine).'), findsOneWidget);
});
test('RunProvider 切换项目时运行任务完全隔离,不发生上一个项目的任务污染', () async {
final projectADir = await Directory.systemTemp.createTemp('project_a_');
final projectBDir = await Directory.systemTemp.createTemp('project_b_');
addTearDown(() async {
if (await projectADir.exists()) await projectADir.delete(recursive: true);
if (await projectBDir.exists()) await projectBDir.delete(recursive: true);
});
final runProvider = RunProvider();
// 1. 打开项目 A,并执行并记录一个任务
await runProvider.onProjectOpened(projectADir.path);
expect(runProvider.currentProjectRoot, equals(projectADir.path));
expect(runProvider.lastRunTask, isNull);
const taskA = RunTask(
id: 'task_a_build',
name: 'Build Project A',
command: 'echo "building A"',
source: TaskSource.custom,
);
await runProvider.addCustomTask(taskA);
await runProvider.setLastRunTask(taskA);
expect(runProvider.lastRunTask?.id, equals('task_a_build'));
expect(runProvider.lastRunTaskId, equals('task_a_build'));
// 2. 切换至项目 B(新项目,无持久化任务)
await runProvider.onProjectOpened(projectBDir.path);
expect(runProvider.currentProjectRoot, equals(projectBDir.path));
// 验证:项目 A 的 lastRunTask 与 customTasks 绝不会泄漏到项目 B!
expect(runProvider.lastRunTask, isNull);
expect(runProvider.lastRunTaskId, isNull);
expect(runProvider.customTasks, isEmpty);
expect(runProvider.allTasks.any((t) => t.id == 'task_a_build'), isFalse);
// 3. 在项目 B 添加并执行任务 B
const taskB = RunTask(
id: 'task_b_test',
name: 'Test Project B',
command: 'pytest',
source: TaskSource.custom,
);
await runProvider.addCustomTask(taskB);
await runProvider.setLastRunTask(taskB);
expect(runProvider.lastRunTask?.id, equals('task_b_test'));
// 4. 切回项目 A,应该恢复项目 A 自身的历史任务
await runProvider.onProjectOpened(projectADir.path);
expect(runProvider.currentProjectRoot, equals(projectADir.path));
expect(runProvider.lastRunTask?.id, equals('task_a_build'));
expect(runProvider.lastRunTaskId, equals('task_a_build'));
expect(runProvider.customTasks.any((t) => t.id == 'task_a_build'), isTrue);
expect(runProvider.customTasks.any((t) => t.id == 'task_b_test'), isFalse);
// 5. 关闭项目
runProvider.onProjectClosed();
expect(runProvider.currentProjectRoot, isNull);
expect(runProvider.lastRunTask, isNull);
expect(runProvider.lastRunTaskId, isNull);
expect(runProvider.allTasks, isEmpty);
});
});
}
+355
View File
@@ -0,0 +1,355 @@
import 'dart:io';
import 'package:code_editor/models/terminal_session.dart';
import 'package:code_editor/services/distro_manager.dart';
import 'package:code_editor/services/toolchain_service.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
void main() {
group('ToolchainService Tool Detection Tests', () {
test('detectRequiredTools extracts compiler and runtime tools correctly', () {
expect(
ToolchainService.detectRequiredTools('make').map((r) => r.checkBinary),
contains('make'),
);
expect(
ToolchainService.detectRequiredTools('cmake -B build && cmake --build build').map((r) => r.checkBinary),
contains('cmake'),
);
expect(
ToolchainService.detectRequiredTools('gcc "./main.c" -o /tmp/a.out && /tmp/a.out').map((r) => r.checkBinary),
contains('gcc'),
);
expect(
ToolchainService.detectRequiredTools('g++ "./main.cpp" -o /tmp/a.out').map((r) => r.checkBinary),
contains('g++'),
);
expect(
ToolchainService.detectRequiredTools('python3 "./script.py"').map((r) => r.checkBinary),
contains('python3'),
);
expect(
ToolchainService.detectRequiredTools('npm start').map((r) => r.checkBinary),
contains('npm'),
);
expect(
ToolchainService.detectRequiredTools('node app.js').map((r) => r.checkBinary),
contains('node'),
);
expect(
ToolchainService.detectRequiredTools('cargo run').map((r) => r.checkBinary),
contains('cargo'),
);
expect(
ToolchainService.detectRequiredTools('rustc main.rs').map((r) => r.checkBinary),
contains('rustc'),
);
expect(
ToolchainService.detectRequiredTools('go run main.go').map((r) => r.checkBinary),
contains('go'),
);
expect(
ToolchainService.detectRequiredTools('./gradlew assembleDebug').map((r) => r.checkBinary),
contains('java'),
);
expect(
ToolchainService.detectRequiredTools('sh ./gradlew run').map((r) => r.checkBinary),
contains('java'),
);
expect(
ToolchainService.detectRequiredTools('echo "hello world" && ls -la'),
isEmpty,
);
});
test('detectRequiredTools deduplicates multiple calls to the same tool', () {
final reqs = ToolchainService.detectRequiredTools('cmake -B build && cmake --build build');
expect(reqs.length, equals(1));
expect(reqs.first.checkBinary, equals('cmake'));
});
});
group('ToolchainService Command Resolution Tests', () {
test('unknown distro returns raw command directly without modification', () {
const cmd = 'make';
final resolved = ToolchainService.resolveCommand(cmd, DistroFamily.unknown);
expect(resolved, equals('make'));
});
test('non-toolchain command returns raw command directly', () {
const cmd = 'echo "test" && ls -la';
final resolved = ToolchainService.resolveCommand(cmd, DistroFamily.ubuntu);
expect(resolved, equals('echo "test" && ls -la'));
});
test('Alpine generates apk install preamble for make', () {
final resolved = ToolchainService.resolveCommand('make', DistroFamily.alpine);
expect(resolved, contains('command -v make'));
expect(resolved, contains('apk update && apk add --no-cache make build-base'));
expect(resolved, contains('make 编译构建工具'));
expect(resolved, endsWith('&& (make)'));
});
test('Ubuntu generates apt-get install preamble for make', () {
final resolved = ToolchainService.resolveCommand('make', DistroFamily.ubuntu);
expect(resolved, contains('command -v make'));
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential'));
expect(resolved, contains('make 编译构建工具'));
expect(resolved, endsWith('&& (make)'));
});
test('Debian generates apt-get install preamble for cmake', () {
final resolved = ToolchainService.resolveCommand('cmake -B build', DistroFamily.debian);
expect(resolved, contains('command -v cmake'));
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential'));
expect(resolved, endsWith('&& (cmake -B build)'));
});
test('Arch generates pacman install preamble for gcc', () {
final resolved = ToolchainService.resolveCommand('gcc main.c', DistroFamily.arch);
expect(resolved, contains('command -v gcc'));
expect(resolved, contains('pacman -Sy --noconfirm base-devel'));
expect(resolved, endsWith('&& (gcc main.c)'));
});
test('Fedora generates dnf install preamble for python3', () {
final resolved = ToolchainService.resolveCommand('python3 app.py', DistroFamily.fedora);
expect(resolved, contains('command -v python3'));
expect(resolved, contains('dnf install -y python3 python3-pip'));
expect(resolved, endsWith('&& (python3 app.py)'));
});
test('Multiple tools generate multiple chained checks', () {
final resolved = ToolchainService.resolveCommand('gcc main.c && python3 test.py', DistroFamily.ubuntu);
expect(resolved, contains('command -v gcc'));
expect(resolved, contains('command -v python3'));
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential'));
expect(resolved, contains('apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip'));
expect(resolved, endsWith('&& (gcc main.c && python3 test.py)'));
});
test('When tool is already physically installed in rootfs, resolveCommand returns raw command without any preamble', () {
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_installed_test_');
try {
final usrBin = Directory(p.join(tempRootfs.path, 'usr', 'bin'))..createSync(recursive: true);
File(p.join(usrBin.path, 'make')).writeAsStringSync('#!/bin/sh\n');
// make 已物理存在于 /usr/bin/make
final resolved = ToolchainService.resolveCommand(
'make',
DistroFamily.debian,
rootDir: tempRootfs,
);
// 核心断言:直接返回原命令 "make",绝不包含任何多余脚本或回显!
expect(resolved, equals('make'));
} finally {
if (tempRootfs.existsSync()) {
try {
tempRootfs.deleteSync(recursive: true);
} catch (_) {}
}
}
});
test('When tool is missing in rootfs, resolveCommand writes /root/.ce_setup.sh and executes it cleanly', () {
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_missing_test_');
try {
final resolved = ToolchainService.resolveCommand(
'make',
DistroFamily.debian,
rootDir: tempRootfs,
);
// 生成了 /root/.ce_setup.sh
final setupFile = File(p.join(tempRootfs.path, 'root', '.ce_setup.sh'));
expect(setupFile.existsSync(), isTrue);
expect(setupFile.readAsStringSync(), contains('build-essential'));
// 终端仅执行简洁命令
expect(resolved, equals('sh /root/.ce_setup.sh && (make)'));
} finally {
if (tempRootfs.existsSync()) {
try {
tempRootfs.deleteSync(recursive: true);
} catch (_) {}
}
}
});
test('When command is a multiline script, resolveCommand writes /root/.ce_task.sh and returns sh /root/.ce_task.sh', () {
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_multiline_test_');
try {
const multilineScript = '''
echo "Step 1: start"
mkdir -p output
echo "done" > output/result.txt
''';
final resolved = ToolchainService.resolveCommand(
multilineScript,
DistroFamily.alpine,
rootDir: tempRootfs,
);
expect(resolved, equals('sh /root/.ce_task.sh'));
final taskFile = File(p.join(tempRootfs.path, 'root', '.ce_task.sh'));
expect(taskFile.existsSync(), isTrue);
final content = taskFile.readAsStringSync();
expect(content, contains('#!/bin/sh'));
expect(content, contains('set -e'));
expect(content, contains('echo "Step 1: start"'));
expect(content, contains('echo "done" > output/result.txt'));
// 确保没有 Windows \r\n
expect(content.contains('\r'), isFalse);
} finally {
if (tempRootfs.existsSync()) {
try {
tempRootfs.deleteSync(recursive: true);
} catch (_) {}
}
}
});
test('Multiline script with missing tools injects installer before script in .ce_task.sh', () {
final tempRootfs = Directory.systemTemp.createTempSync('rootfs_multiline_tool_test_');
try {
const multilineScript = '''
gcc main.c -o app
./app
''';
final resolved = ToolchainService.resolveCommand(
multilineScript,
DistroFamily.debian,
rootDir: tempRootfs,
);
expect(resolved, equals('sh /root/.ce_task.sh'));
final taskFile = File(p.join(tempRootfs.path, 'root', '.ce_task.sh'));
expect(taskFile.existsSync(), isTrue);
final content = taskFile.readAsStringSync();
// 验证同时包含了安装引导与用户脚本
expect(content, contains('build-essential'));
expect(content, contains('gcc main.c -o app'));
} finally {
if (tempRootfs.existsSync()) {
try {
tempRootfs.deleteSync(recursive: true);
} catch (_) {}
}
}
});
});
group('DistroManager detectDistroFamily Tests', () {
late Directory tempBaseDir;
late DistroManager manager;
setUp(() {
tempBaseDir = Directory.systemTemp.createTempSync('distro_detect_test_');
manager = DistroManager();
manager.customBaseDir = tempBaseDir;
});
tearDown(() {
if (tempBaseDir.existsSync()) {
try {
tempBaseDir.deleteSync(recursive: true);
} catch (_) {}
}
manager.customBaseDir = null;
});
test('detects Alpine correctly from apk directory and release file', () async {
final rootfs = Directory(p.join(tempBaseDir.path, 'my_alpine', 'rootfs'));
Directory(p.join(rootfs.path, 'etc', 'apk')).createSync(recursive: true);
File(p.join(rootfs.path, 'etc', 'alpine-release')).writeAsStringSync('3.20.3\n');
final family = await manager.detectDistroFamily('my_alpine');
expect(family, equals(DistroFamily.alpine));
});
test('detects Ubuntu correctly from os-release and apt directory', () async {
final rootfs = Directory(p.join(tempBaseDir.path, 'ubuntu_dev', 'rootfs'));
Directory(p.join(rootfs.path, 'etc', 'apt')).createSync(recursive: true);
File(p.join(rootfs.path, 'etc', 'os-release')).writeAsStringSync('NAME="Ubuntu"\nID=ubuntu\nVERSION_ID="24.04"\n');
final family = await manager.detectDistroFamily('ubuntu_dev');
expect(family, equals(DistroFamily.ubuntu));
});
test('detects Debian correctly when apt is present without ubuntu markers', () async {
final rootfs = Directory(p.join(tempBaseDir.path, 'debian_sys', 'rootfs'));
Directory(p.join(rootfs.path, 'etc', 'apt')).createSync(recursive: true);
File(p.join(rootfs.path, 'etc', 'os-release')).writeAsStringSync('NAME="Debian GNU/Linux"\nID=debian\n');
final family = await manager.detectDistroFamily('debian_sys');
expect(family, equals(DistroFamily.debian));
});
test('detects Arch Linux correctly from pacman.d directory', () async {
final rootfs = Directory(p.join(tempBaseDir.path, 'arch_sys', 'rootfs'));
Directory(p.join(rootfs.path, 'etc', 'pacman.d')).createSync(recursive: true);
final family = await manager.detectDistroFamily('arch_sys');
expect(family, equals(DistroFamily.arch));
});
test('detects Fedora correctly from yum.repos.d directory', () async {
final rootfs = Directory(p.join(tempBaseDir.path, 'fedora_sys', 'rootfs'));
Directory(p.join(rootfs.path, 'etc', 'yum.repos.d')).createSync(recursive: true);
final family = await manager.detectDistroFamily('fedora_sys');
expect(family, equals(DistroFamily.fedora));
});
test('returns unknown for host system or unrecognized custom distro', () async {
expect(await manager.detectDistroFamily('host'), equals(DistroFamily.unknown));
final rootfs = Directory(p.join(tempBaseDir.path, 'custom_sys', 'rootfs'));
Directory(p.join(rootfs.path, 'etc')).createSync(recursive: true);
expect(await manager.detectDistroFamily('custom_sys'), equals(DistroFamily.unknown));
expect(await manager.detectDistroFamily('non_existent'), equals(DistroFamily.unknown));
});
});
group('TerminalSession executeCommand Tests', () {
test('executeCommand reports unstarted when PTY launch fails or is unstarted', () async {
final session = TerminalSession(
id: 'test_session',
autoStartProcess: false,
);
await session.executeCommand('echo test');
expect(session.bufferText, contains('无法执行命令:终端环境未启动或启动失败'));
session.dispose();
});
test('clear resets terminal screen', () {
final session = TerminalSession(
id: 'test_clear_session',
autoStartProcess: false,
);
session.write('Some previous output');
session.clear();
// clear emits VT100 ANSI sequences
expect(session.bufferText.trim(), isEmpty);
session.dispose();
});
});
}
+3 -3
View File
@@ -2103,9 +2103,6 @@ void main() {
await tester.scrollUntilVisible(find.text('终端小键盘'), 200);
expect(find.text('终端小键盘'), findsOneWidget);
await tester.scrollUntilVisible(find.text('编辑终端键盘配置'), 200);
expect(find.text('编辑终端键盘配置'), findsOneWidget);
// 关闭终端小键盘后,配置入口被禁用但编辑区的仍可用
final terminalSwitch = find.descendant(
of: find.widgetWithText(SwitchListTile, '终端小键盘'),
@@ -2119,6 +2116,9 @@ void main() {
await tester.pumpAndSettle();
expect(settingsProvider.keyboardEnabledFor(KeyboardScope.terminal), isTrue);
await tester.scrollUntilVisible(find.text('编辑终端键盘配置'), 200);
expect(find.text('编辑终端键盘配置'), findsOneWidget);
// 进入终端键盘配置页:副标题显示“终端”
final editorJsonBefore = settingsProvider.keyboardConfigJsonFor(KeyboardScope.editor);
await tester.tap(find.text('编辑终端键盘配置'));
+1 -1
View File
@@ -35,7 +35,7 @@ param(
)
$ErrorActionPreference = "Stop"
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
Set-Location $root
# --- 工具链 ---------------------------------------------------------------
+21 -23
View File
@@ -1,7 +1,5 @@
warning: in the working copy of 'src/syscall/seccomp.c', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/syscall/legacy.c', LF will be replaced by CRLF the next time Git touches it
diff --git a/src/GNUmakefile b/src/GNUmakefile
index 5ade279..4a85331 100644
index 5ade279..f2a5c22 100644
--- a/src/GNUmakefile
+++ b/src/GNUmakefile
@@ -46,6 +46,7 @@ OBJECTS += \
@@ -12,15 +10,8 @@ index 5ade279..4a85331 100644
syscall/socket.o \
syscall/heap.o \
syscall/rlimit.o \
@@ -280,4 +281,4 @@ ifdef PROOT_UNBUNDLE_LOADER
ifdef HAS_LOADER_32BIT
$(INSTALL) -D loader/loader-m32 $(PROOT_UNBUNDLE_LOADER)/loader32
endif
-endif
+endif
\ No newline at end of file
diff --git a/src/syscall/enter.c b/src/syscall/enter.c
index 93f4306..0f72da3 100644
index 93f4306..a45d00d 100644
--- a/src/syscall/enter.c
+++ b/src/syscall/enter.c
@@ -79,6 +79,7 @@
@@ -31,7 +22,7 @@ index 93f4306..0f72da3 100644
/* Older kernel headers may lack these. */
#ifndef CLONE_NEWTIME
@@ -1837,6 +1838,9 @@ int translate_syscall_enter(Tracee *tracee)
@@ -1837,8 +1838,11 @@ int translate_syscall_enter(Tracee *tracee)
if (status > 0)
return 0;
@@ -39,21 +30,17 @@ index 93f4306..0f72da3 100644
+ translate_legacy_syscall(tracee);
+
/* Translate input arguments. */
syscall_number = get_sysnum(tracee, ORIGINAL);
- syscall_number = get_sysnum(tracee, ORIGINAL);
+ syscall_number = get_sysnum(tracee, CURRENT);
switch (syscall_number) {
@@ -2869,4 +2873,4 @@ end:
status = status2;
return status;
-}
+}
\ No newline at end of file
default:
/* Nothing to do. */
diff --git a/src/syscall/legacy.c b/src/syscall/legacy.c
new file mode 100644
index 0000000..1e6dcf1
index 0000000..d65f808
--- /dev/null
+++ b/src/syscall/legacy.c
@@ -0,0 +1,298 @@
@@ -0,0 +1,310 @@
+/* -*- c-set-style: "K&R"; c-basic-offset: 8 -*- */
+/*
+ * Legacy SysV-era syscall modernization for Android app processes.
@@ -273,15 +260,26 @@ index 0000000..1e6dcf1
+
+ /* With CLONE_PIDFD the pidfd is written through the parent_tid slot. */
+ parent_tid = (flags & CLONE_PIDFD) != 0 ? (word_t) a.pidfd
warning: in the working copy of 'src/syscall/legacy.h', LF will be replaced by CRLF the next time Git touches it
+ : (word_t) a.parent_tid;
+
+ poke_reg(tracee, SYSARG_1, (word_t) flags);
+ /* classic clone() wants the *top* of the child stack */
+ poke_reg(tracee, SYSARG_2, (word_t)(a.stack + a.stack_size));
+ poke_reg(tracee, SYSARG_3, parent_tid);
+
+ /* Linux sys_clone ABI:
+ * x86_64: sys_clone(flags, newsp, parent_tid, child_tid, tls)
+ * SYSARG_4 = child_tid, SYSARG_5 = tls
+ * arm/arm64: sys_clone(flags, newsp, parent_tid, tls, child_tid)
+ * SYSARG_4 = tls, SYSARG_5 = child_tid
+ */
+#if defined(ARCH_ARM64) || defined(ARCH_ARM_EABI) || defined(__aarch64__) || defined(__arm__)
+ poke_reg(tracee, SYSARG_4, (word_t) a.tls);
+ poke_reg(tracee, SYSARG_5, (word_t) a.child_tid);
+#else
+ poke_reg(tracee, SYSARG_4, (word_t) a.child_tid);
+ poke_reg(tracee, SYSARG_5, (word_t) a.tls);
+#endif
+
+ set_sysnum(tracee, PR_clone);
+}