From 4614825b7f0e3936e8ce8bb1c17ee7a4eed3c264 Mon Sep 17 00:00:00 2001 From: LZX <1820455493@qq.com> Date: Fri, 18 Sep 2026 20:40:36 +0800 Subject: [PATCH] 1 --- android/app/src/main/AndroidManifest.xml | 10 + lib/l10n/app_en.arb | 62 +- lib/l10n/app_localizations.dart | 300 +++++++ lib/l10n/app_localizations_en.dart | 163 ++++ lib/l10n/app_localizations_zh.dart | 160 ++++ lib/l10n/app_zh.arb | 62 +- lib/models/git_account.dart | 170 ++++ lib/models/lsp_language_config.dart | 356 +++++++- lib/providers/git_provider.dart | 19 + lib/services/distro_manager.dart | 3 +- lib/services/git_account_service.dart | 480 +++++++++++ lib/services/git_service.dart | 10 +- lib/services/internal_engine_service.dart | 55 +- lib/services/lsp/lsp_manager.dart | 10 +- lib/services/lsp_config_service.dart | 23 +- lib/services/toolchain_service.dart | 2 +- .../code_completion_management_view.dart | 6 +- lib/views/git_account_management_view.dart | 815 ++++++++++++++++++ lib/views/main_view.dart | 13 +- lib/widgets/git/git_panel_widget.dart | 280 +++--- linux/flutter/generated_plugin_registrant.cc | 4 + linux/flutter/generated_plugins.cmake | 1 + macos/Flutter/GeneratedPluginRegistrant.swift | 2 + pubspec.lock | 64 ++ pubspec.yaml | 1 + test/container_runtime_chroot_test.dart | 15 + test/git_account_test.dart | 275 ++++++ test/widget_test.dart | 19 + .../flutter/generated_plugin_registrant.cc | 3 + windows/flutter/generated_plugins.cmake | 1 + 30 files changed, 3226 insertions(+), 158 deletions(-) create mode 100644 lib/models/git_account.dart create mode 100644 lib/services/git_account_service.dart create mode 100644 lib/views/git_account_management_view.dart create mode 100644 test/git_account_test.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 72198cf..8b7ddda 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -65,5 +65,15 @@ + + + + + + + + + + diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 327f8d5..172c77e 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1333,5 +1333,65 @@ "searchRefresh": "Refresh", "searchPreviousMatch": "Previous Match", "searchNextMatch": "Next Match", - "replaceCurrentMatch": "Replace" + "replaceCurrentMatch": "Replace", + "gitAccountManagement": "Git Accounts", + "gitEdit": "Edit", + "gitHostedAccounts": "Hosted Accounts", + "gitSshKeys": "SSH Keys", + "gitAddAccount": "Add Git Account", + "gitEditAccount": "Edit Git Account", + "gitNoAccountsTitle": "No Git Accounts Connected", + "gitNoAccountsSubtitle": "Connect GitHub, Gitee, etc. for seamless passwordless pushing and pulling.", + "gitAddFirstAccount": "Add First Git Account", + "gitDefaultAccountBadge": "Default", + "gitSetAsDefault": "Set as Default", + "gitSetAsDefaultSuccess": "Set as default account", + "gitTestConnection": "Test Connection", + "gitTestingConnection": "Testing platform connection...", + "gitTestConnectionSuccess": "Connection successful! Verified user: {username}", + "@gitTestConnectionSuccess": { + "placeholders": { + "username": { "type": "String" } + } + }, + "gitTestConnectionFailed": "Verification failed", + "gitDeleteAccount": "Delete Account", + "gitDeleteAccountConfirmTitle": "Delete account {name}?", + "@gitDeleteAccountConfirmTitle": { + "placeholders": { + "name": { "type": "String" } + } + }, + "gitDeleteAccountConfirmMessage": "Credentials will be removed from local storage and the container. Remote operations will require re-authentication.", + "gitDeleteAccountSuccess": "Account deleted", + "gitAccountSavedSuccess": "Account added successfully", + "gitAccountUpdatedSuccess": "Account updated successfully", + "gitContainerSshTitle": "Container Built-in SSH Key", + "gitContainerSshSubtitle": "Used for SSH clone and push (git@github.com:... or git@gitee.com:...).", + "gitCopyPublicKey": "Copy Public Key", + "gitPublicKeyCopied": "Public key copied to clipboard", + "gitRegenerateKey": "Regenerate", + "gitNoSshKeyNotice": "No SSH key pair generated yet. Once generated, you can copy and paste it into GitHub/Gitee SSH Keys settings.", + "gitGenerateEd25519Key": "Generate Ed25519 SSH Key", + "gitGeneratingSshKey": "Generating SSH Key...", + "gitSshKeyGenerateSuccess": "SSH key generated successfully", + "gitSshKeyGenerateFailed": "Generation failed", + "gitRegenerateSshConfirmTitle": "Regenerate SSH Key?", + "gitRegenerateSshConfirmMessage": "Regenerating will overwrite the existing key. The old public key on GitHub/Gitee will become invalid.", + "gitOverwrite": "Overwrite", + "gitSshGuideTitle": "How to configure on cloud platforms?", + "gitSshGuideStep1": "Click [Copy Public Key] above;", + "gitSshGuideStep2": "Open GitHub or Gitee settings in browser (Settings -> SSH Keys);", + "gitSshGuideStep3": "Click \"New SSH Key\", paste the public key into the Key field and save.", + "gitServerUrl": "Server URL", + "gitTokenLabel": "Personal Access Token", + "gitTokenHint": "Enter PAT created on platform", + "gitGetToken": "Get Token", + "gitTokenCopiedOpeningBrowser": "Token URL copied, opening browser...", + "gitEnterTokenPrompt": "Please enter Personal Access Token", + "gitTokenVerifyFailed": "Token verification failed. Please check permissions or validity", + "gitVerifyAndSave": "Verify & Save", + "gitAuthTypeToken": "Personal Access Token", + "gitAuthTypeSsh": "SSH Key Pair", + "gitPlatformGeneric": "Generic / Self-hosted Git" } \ No newline at end of file diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 869bde1..c74306e 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3909,6 +3909,306 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'替换'** String get replaceCurrentMatch; + + /// No description provided for @gitAccountManagement. + /// + /// In zh, this message translates to: + /// **'Git 账号管理'** + String get gitAccountManagement; + + /// No description provided for @gitEdit. + /// + /// In zh, this message translates to: + /// **'编辑'** + String get gitEdit; + + /// No description provided for @gitHostedAccounts. + /// + /// In zh, this message translates to: + /// **'托管账号'** + String get gitHostedAccounts; + + /// No description provided for @gitSshKeys. + /// + /// In zh, this message translates to: + /// **'SSH 密钥'** + String get gitSshKeys; + + /// No description provided for @gitAddAccount. + /// + /// In zh, this message translates to: + /// **'添加 Git 账号'** + String get gitAddAccount; + + /// No description provided for @gitEditAccount. + /// + /// In zh, this message translates to: + /// **'编辑 Git 账号'** + String get gitEditAccount; + + /// No description provided for @gitNoAccountsTitle. + /// + /// In zh, this message translates to: + /// **'暂未绑定 Git 账号'** + String get gitNoAccountsTitle; + + /// No description provided for @gitNoAccountsSubtitle. + /// + /// In zh, this message translates to: + /// **'绑定 GitHub 或 Gitee 等账号后,推送代码、拉取私有仓库将全程免密认证。'** + String get gitNoAccountsSubtitle; + + /// No description provided for @gitAddFirstAccount. + /// + /// In zh, this message translates to: + /// **'添加第一个 Git 账号'** + String get gitAddFirstAccount; + + /// No description provided for @gitDefaultAccountBadge. + /// + /// In zh, this message translates to: + /// **'默认'** + String get gitDefaultAccountBadge; + + /// No description provided for @gitSetAsDefault. + /// + /// In zh, this message translates to: + /// **'设为默认账号'** + String get gitSetAsDefault; + + /// No description provided for @gitSetAsDefaultSuccess. + /// + /// In zh, this message translates to: + /// **'已设为默认账号'** + String get gitSetAsDefaultSuccess; + + /// No description provided for @gitTestConnection. + /// + /// In zh, this message translates to: + /// **'测试连接'** + String get gitTestConnection; + + /// No description provided for @gitTestingConnection. + /// + /// In zh, this message translates to: + /// **'正在验证平台连接...'** + String get gitTestingConnection; + + /// No description provided for @gitTestConnectionSuccess. + /// + /// In zh, this message translates to: + /// **'连接成功!已验证用户: {username}'** + String gitTestConnectionSuccess(String username); + + /// No description provided for @gitTestConnectionFailed. + /// + /// In zh, this message translates to: + /// **'验证失败'** + String get gitTestConnectionFailed; + + /// No description provided for @gitDeleteAccount. + /// + /// In zh, this message translates to: + /// **'删除账号'** + String get gitDeleteAccount; + + /// No description provided for @gitDeleteAccountConfirmTitle. + /// + /// In zh, this message translates to: + /// **'删除账号 {name}?'** + String gitDeleteAccountConfirmTitle(String name); + + /// No description provided for @gitDeleteAccountConfirmMessage. + /// + /// In zh, this message translates to: + /// **'删除后该账号凭据将从本地及容器内移除,相关远程操作将需要重新认证。'** + String get gitDeleteAccountConfirmMessage; + + /// No description provided for @gitDeleteAccountSuccess. + /// + /// In zh, this message translates to: + /// **'已删除账号'** + String get gitDeleteAccountSuccess; + + /// No description provided for @gitAccountSavedSuccess. + /// + /// In zh, this message translates to: + /// **'账号添加成功'** + String get gitAccountSavedSuccess; + + /// No description provided for @gitAccountUpdatedSuccess. + /// + /// In zh, this message translates to: + /// **'账号已更新'** + String get gitAccountUpdatedSuccess; + + /// No description provided for @gitContainerSshTitle. + /// + /// In zh, this message translates to: + /// **'容器内置 SSH 密钥对'** + String get gitContainerSshTitle; + + /// No description provided for @gitContainerSshSubtitle. + /// + /// In zh, this message translates to: + /// **'用于 SSH 协议免密克隆与推送 (git@github.com:... 或 git@gitee.com:...)。'** + String get gitContainerSshSubtitle; + + /// No description provided for @gitCopyPublicKey. + /// + /// In zh, this message translates to: + /// **'一键复制公钥'** + String get gitCopyPublicKey; + + /// No description provided for @gitPublicKeyCopied. + /// + /// In zh, this message translates to: + /// **'公钥已复制到剪贴板'** + String get gitPublicKeyCopied; + + /// No description provided for @gitRegenerateKey. + /// + /// In zh, this message translates to: + /// **'重新生成'** + String get gitRegenerateKey; + + /// No description provided for @gitNoSshKeyNotice. + /// + /// In zh, this message translates to: + /// **'当前尚未生成 SSH 密钥对。生成后即可一键复制并粘贴至 GitHub/Gitee 的 SSH Keys 设置中。'** + String get gitNoSshKeyNotice; + + /// No description provided for @gitGenerateEd25519Key. + /// + /// In zh, this message translates to: + /// **'生成 Ed25519 SSH 密钥'** + String get gitGenerateEd25519Key; + + /// No description provided for @gitGeneratingSshKey. + /// + /// In zh, this message translates to: + /// **'正在生成 SSH 密钥...'** + String get gitGeneratingSshKey; + + /// No description provided for @gitSshKeyGenerateSuccess. + /// + /// In zh, this message translates to: + /// **'SSH 密钥生成成功'** + String get gitSshKeyGenerateSuccess; + + /// No description provided for @gitSshKeyGenerateFailed. + /// + /// In zh, this message translates to: + /// **'生成失败'** + String get gitSshKeyGenerateFailed; + + /// No description provided for @gitRegenerateSshConfirmTitle. + /// + /// In zh, this message translates to: + /// **'重新生成 SSH 密钥?'** + String get gitRegenerateSshConfirmTitle; + + /// No description provided for @gitRegenerateSshConfirmMessage. + /// + /// In zh, this message translates to: + /// **'重新生成将覆盖现有的 SSH 密钥,旧公钥在 GitHub/Gitee 上将失效,需重新粘贴新公钥。'** + String get gitRegenerateSshConfirmMessage; + + /// No description provided for @gitOverwrite. + /// + /// In zh, this message translates to: + /// **'确定覆盖'** + String get gitOverwrite; + + /// No description provided for @gitSshGuideTitle. + /// + /// In zh, this message translates to: + /// **'如何配置到云端平台?'** + String get gitSshGuideTitle; + + /// No description provided for @gitSshGuideStep1. + /// + /// In zh, this message translates to: + /// **'点击上方【一键复制公钥】;'** + String get gitSshGuideStep1; + + /// No description provided for @gitSshGuideStep2. + /// + /// In zh, this message translates to: + /// **'在浏览器打开 GitHub 或 Gitee 的设置页 (Settings -> SSH Keys);'** + String get gitSshGuideStep2; + + /// No description provided for @gitSshGuideStep3. + /// + /// In zh, this message translates to: + /// **'点击 \"New SSH Key\",将公钥粘贴到 Key 输入框中保存即可。'** + String get gitSshGuideStep3; + + /// No description provided for @gitServerUrl. + /// + /// In zh, this message translates to: + /// **'服务器地址'** + String get gitServerUrl; + + /// No description provided for @gitTokenLabel. + /// + /// In zh, this message translates to: + /// **'访问令牌'** + String get gitTokenLabel; + + /// No description provided for @gitTokenHint. + /// + /// In zh, this message translates to: + /// **'输入在平台创建的 PAT 令牌'** + String get gitTokenHint; + + /// No description provided for @gitGetToken. + /// + /// In zh, this message translates to: + /// **'获取 Token'** + String get gitGetToken; + + /// No description provided for @gitTokenCopiedOpeningBrowser. + /// + /// In zh, this message translates to: + /// **'Token 创建链接已复制,正在前往浏览器...'** + String get gitTokenCopiedOpeningBrowser; + + /// No description provided for @gitEnterTokenPrompt. + /// + /// In zh, this message translates to: + /// **'请输入访问令牌'** + String get gitEnterTokenPrompt; + + /// No description provided for @gitTokenVerifyFailed. + /// + /// In zh, this message translates to: + /// **'Token 校验失败,请核对权限或有效性'** + String get gitTokenVerifyFailed; + + /// No description provided for @gitVerifyAndSave. + /// + /// In zh, this message translates to: + /// **'验证并保存'** + String get gitVerifyAndSave; + + /// No description provided for @gitAuthTypeToken. + /// + /// In zh, this message translates to: + /// **'个人访问令牌'** + String get gitAuthTypeToken; + + /// No description provided for @gitAuthTypeSsh. + /// + /// In zh, this message translates to: + /// **'SSH 密钥对'** + String get gitAuthTypeSsh; + + /// No description provided for @gitPlatformGeneric. + /// + /// In zh, this message translates to: + /// **'通用 / 自建 Git'** + String get gitPlatformGeneric; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index ff57a41..7475b84 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2329,4 +2329,167 @@ class AppLocalizationsEn extends AppLocalizations { @override String get replaceCurrentMatch => 'Replace'; + + @override + String get gitAccountManagement => 'Git Accounts'; + + @override + String get gitEdit => 'Edit'; + + @override + String get gitHostedAccounts => 'Hosted Accounts'; + + @override + String get gitSshKeys => 'SSH Keys'; + + @override + String get gitAddAccount => 'Add Git Account'; + + @override + String get gitEditAccount => 'Edit Git Account'; + + @override + String get gitNoAccountsTitle => 'No Git Accounts Connected'; + + @override + String get gitNoAccountsSubtitle => + 'Connect GitHub, Gitee, etc. for seamless passwordless pushing and pulling.'; + + @override + String get gitAddFirstAccount => 'Add First Git Account'; + + @override + String get gitDefaultAccountBadge => 'Default'; + + @override + String get gitSetAsDefault => 'Set as Default'; + + @override + String get gitSetAsDefaultSuccess => 'Set as default account'; + + @override + String get gitTestConnection => 'Test Connection'; + + @override + String get gitTestingConnection => 'Testing platform connection...'; + + @override + String gitTestConnectionSuccess(String username) { + return 'Connection successful! Verified user: $username'; + } + + @override + String get gitTestConnectionFailed => 'Verification failed'; + + @override + String get gitDeleteAccount => 'Delete Account'; + + @override + String gitDeleteAccountConfirmTitle(String name) { + return 'Delete account $name?'; + } + + @override + String get gitDeleteAccountConfirmMessage => + 'Credentials will be removed from local storage and the container. Remote operations will require re-authentication.'; + + @override + String get gitDeleteAccountSuccess => 'Account deleted'; + + @override + String get gitAccountSavedSuccess => 'Account added successfully'; + + @override + String get gitAccountUpdatedSuccess => 'Account updated successfully'; + + @override + String get gitContainerSshTitle => 'Container Built-in SSH Key'; + + @override + String get gitContainerSshSubtitle => + 'Used for SSH clone and push (git@github.com:... or git@gitee.com:...).'; + + @override + String get gitCopyPublicKey => 'Copy Public Key'; + + @override + String get gitPublicKeyCopied => 'Public key copied to clipboard'; + + @override + String get gitRegenerateKey => 'Regenerate'; + + @override + String get gitNoSshKeyNotice => + 'No SSH key pair generated yet. Once generated, you can copy and paste it into GitHub/Gitee SSH Keys settings.'; + + @override + String get gitGenerateEd25519Key => 'Generate Ed25519 SSH Key'; + + @override + String get gitGeneratingSshKey => 'Generating SSH Key...'; + + @override + String get gitSshKeyGenerateSuccess => 'SSH key generated successfully'; + + @override + String get gitSshKeyGenerateFailed => 'Generation failed'; + + @override + String get gitRegenerateSshConfirmTitle => 'Regenerate SSH Key?'; + + @override + String get gitRegenerateSshConfirmMessage => + 'Regenerating will overwrite the existing key. The old public key on GitHub/Gitee will become invalid.'; + + @override + String get gitOverwrite => 'Overwrite'; + + @override + String get gitSshGuideTitle => 'How to configure on cloud platforms?'; + + @override + String get gitSshGuideStep1 => 'Click [Copy Public Key] above;'; + + @override + String get gitSshGuideStep2 => + 'Open GitHub or Gitee settings in browser (Settings -> SSH Keys);'; + + @override + String get gitSshGuideStep3 => + 'Click \"New SSH Key\", paste the public key into the Key field and save.'; + + @override + String get gitServerUrl => 'Server URL'; + + @override + String get gitTokenLabel => 'Personal Access Token'; + + @override + String get gitTokenHint => 'Enter PAT created on platform'; + + @override + String get gitGetToken => 'Get Token'; + + @override + String get gitTokenCopiedOpeningBrowser => + 'Token URL copied, opening browser...'; + + @override + String get gitEnterTokenPrompt => 'Please enter Personal Access Token'; + + @override + String get gitTokenVerifyFailed => + 'Token verification failed. Please check permissions or validity'; + + @override + String get gitVerifyAndSave => 'Verify & Save'; + + @override + String get gitAuthTypeToken => 'Personal Access Token'; + + @override + String get gitAuthTypeSsh => 'SSH Key Pair'; + + @override + String get gitPlatformGeneric => 'Generic / Self-hosted Git'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 9bb6553..a79a7ed 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2264,4 +2264,164 @@ class AppLocalizationsZh extends AppLocalizations { @override String get replaceCurrentMatch => '替换'; + + @override + String get gitAccountManagement => 'Git 账号管理'; + + @override + String get gitEdit => '编辑'; + + @override + String get gitHostedAccounts => '托管账号'; + + @override + String get gitSshKeys => 'SSH 密钥'; + + @override + String get gitAddAccount => '添加 Git 账号'; + + @override + String get gitEditAccount => '编辑 Git 账号'; + + @override + String get gitNoAccountsTitle => '暂未绑定 Git 账号'; + + @override + String get gitNoAccountsSubtitle => + '绑定 GitHub 或 Gitee 等账号后,推送代码、拉取私有仓库将全程免密认证。'; + + @override + String get gitAddFirstAccount => '添加第一个 Git 账号'; + + @override + String get gitDefaultAccountBadge => '默认'; + + @override + String get gitSetAsDefault => '设为默认账号'; + + @override + String get gitSetAsDefaultSuccess => '已设为默认账号'; + + @override + String get gitTestConnection => '测试连接'; + + @override + String get gitTestingConnection => '正在验证平台连接...'; + + @override + String gitTestConnectionSuccess(String username) { + return '连接成功!已验证用户: $username'; + } + + @override + String get gitTestConnectionFailed => '验证失败'; + + @override + String get gitDeleteAccount => '删除账号'; + + @override + String gitDeleteAccountConfirmTitle(String name) { + return '删除账号 $name?'; + } + + @override + String get gitDeleteAccountConfirmMessage => + '删除后该账号凭据将从本地及容器内移除,相关远程操作将需要重新认证。'; + + @override + String get gitDeleteAccountSuccess => '已删除账号'; + + @override + String get gitAccountSavedSuccess => '账号添加成功'; + + @override + String get gitAccountUpdatedSuccess => '账号已更新'; + + @override + String get gitContainerSshTitle => '容器内置 SSH 密钥对'; + + @override + String get gitContainerSshSubtitle => + '用于 SSH 协议免密克隆与推送 (git@github.com:... 或 git@gitee.com:...)。'; + + @override + String get gitCopyPublicKey => '一键复制公钥'; + + @override + String get gitPublicKeyCopied => '公钥已复制到剪贴板'; + + @override + String get gitRegenerateKey => '重新生成'; + + @override + String get gitNoSshKeyNotice => + '当前尚未生成 SSH 密钥对。生成后即可一键复制并粘贴至 GitHub/Gitee 的 SSH Keys 设置中。'; + + @override + String get gitGenerateEd25519Key => '生成 Ed25519 SSH 密钥'; + + @override + String get gitGeneratingSshKey => '正在生成 SSH 密钥...'; + + @override + String get gitSshKeyGenerateSuccess => 'SSH 密钥生成成功'; + + @override + String get gitSshKeyGenerateFailed => '生成失败'; + + @override + String get gitRegenerateSshConfirmTitle => '重新生成 SSH 密钥?'; + + @override + String get gitRegenerateSshConfirmMessage => + '重新生成将覆盖现有的 SSH 密钥,旧公钥在 GitHub/Gitee 上将失效,需重新粘贴新公钥。'; + + @override + String get gitOverwrite => '确定覆盖'; + + @override + String get gitSshGuideTitle => '如何配置到云端平台?'; + + @override + String get gitSshGuideStep1 => '点击上方【一键复制公钥】;'; + + @override + String get gitSshGuideStep2 => + '在浏览器打开 GitHub 或 Gitee 的设置页 (Settings -> SSH Keys);'; + + @override + String get gitSshGuideStep3 => '点击 \"New SSH Key\",将公钥粘贴到 Key 输入框中保存即可。'; + + @override + String get gitServerUrl => '服务器地址'; + + @override + String get gitTokenLabel => '访问令牌'; + + @override + String get gitTokenHint => '输入在平台创建的 PAT 令牌'; + + @override + String get gitGetToken => '获取 Token'; + + @override + String get gitTokenCopiedOpeningBrowser => 'Token 创建链接已复制,正在前往浏览器...'; + + @override + String get gitEnterTokenPrompt => '请输入访问令牌'; + + @override + String get gitTokenVerifyFailed => 'Token 校验失败,请核对权限或有效性'; + + @override + String get gitVerifyAndSave => '验证并保存'; + + @override + String get gitAuthTypeToken => '个人访问令牌'; + + @override + String get gitAuthTypeSsh => 'SSH 密钥对'; + + @override + String get gitPlatformGeneric => '通用 / 自建 Git'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6df2e55..9e752c8 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -1333,5 +1333,65 @@ "searchRefresh": "刷新", "searchPreviousMatch": "上一个匹配项", "searchNextMatch": "下一个匹配项", - "replaceCurrentMatch": "替换" + "replaceCurrentMatch": "替换", + "gitAccountManagement": "Git 账号管理", + "gitEdit": "编辑", + "gitHostedAccounts": "托管账号", + "gitSshKeys": "SSH 密钥", + "gitAddAccount": "添加 Git 账号", + "gitEditAccount": "编辑 Git 账号", + "gitNoAccountsTitle": "暂未绑定 Git 账号", + "gitNoAccountsSubtitle": "绑定 GitHub 或 Gitee 等账号后,推送代码、拉取私有仓库将全程免密认证。", + "gitAddFirstAccount": "添加第一个 Git 账号", + "gitDefaultAccountBadge": "默认", + "gitSetAsDefault": "设为默认账号", + "gitSetAsDefaultSuccess": "已设为默认账号", + "gitTestConnection": "测试连接", + "gitTestingConnection": "正在验证平台连接...", + "gitTestConnectionSuccess": "连接成功!已验证用户: {username}", + "@gitTestConnectionSuccess": { + "placeholders": { + "username": { "type": "String" } + } + }, + "gitTestConnectionFailed": "验证失败", + "gitDeleteAccount": "删除账号", + "gitDeleteAccountConfirmTitle": "删除账号 {name}?", + "@gitDeleteAccountConfirmTitle": { + "placeholders": { + "name": { "type": "String" } + } + }, + "gitDeleteAccountConfirmMessage": "删除后该账号凭据将从本地及容器内移除,相关远程操作将需要重新认证。", + "gitDeleteAccountSuccess": "已删除账号", + "gitAccountSavedSuccess": "账号添加成功", + "gitAccountUpdatedSuccess": "账号已更新", + "gitContainerSshTitle": "容器内置 SSH 密钥对", + "gitContainerSshSubtitle": "用于 SSH 协议免密克隆与推送 (git@github.com:... 或 git@gitee.com:...)。", + "gitCopyPublicKey": "一键复制公钥", + "gitPublicKeyCopied": "公钥已复制到剪贴板", + "gitRegenerateKey": "重新生成", + "gitNoSshKeyNotice": "当前尚未生成 SSH 密钥对。生成后即可一键复制并粘贴至 GitHub/Gitee 的 SSH Keys 设置中。", + "gitGenerateEd25519Key": "生成 Ed25519 SSH 密钥", + "gitGeneratingSshKey": "正在生成 SSH 密钥...", + "gitSshKeyGenerateSuccess": "SSH 密钥生成成功", + "gitSshKeyGenerateFailed": "生成失败", + "gitRegenerateSshConfirmTitle": "重新生成 SSH 密钥?", + "gitRegenerateSshConfirmMessage": "重新生成将覆盖现有的 SSH 密钥,旧公钥在 GitHub/Gitee 上将失效,需重新粘贴新公钥。", + "gitOverwrite": "确定覆盖", + "gitSshGuideTitle": "如何配置到云端平台?", + "gitSshGuideStep1": "点击上方【一键复制公钥】;", + "gitSshGuideStep2": "在浏览器打开 GitHub 或 Gitee 的设置页 (Settings -> SSH Keys);", + "gitSshGuideStep3": "点击 \"New SSH Key\",将公钥粘贴到 Key 输入框中保存即可。", + "gitServerUrl": "服务器地址", + "gitTokenLabel": "访问令牌", + "gitTokenHint": "输入在平台创建的 PAT 令牌", + "gitGetToken": "获取 Token", + "gitTokenCopiedOpeningBrowser": "Token 创建链接已复制,正在前往浏览器...", + "gitEnterTokenPrompt": "请输入访问令牌", + "gitTokenVerifyFailed": "Token 校验失败,请核对权限或有效性", + "gitVerifyAndSave": "验证并保存", + "gitAuthTypeToken": "个人访问令牌", + "gitAuthTypeSsh": "SSH 密钥对", + "gitPlatformGeneric": "通用 / 自建 Git" } \ No newline at end of file diff --git a/lib/models/git_account.dart b/lib/models/git_account.dart new file mode 100644 index 0000000..6ceb8ab --- /dev/null +++ b/lib/models/git_account.dart @@ -0,0 +1,170 @@ +import 'package:flutter/material.dart'; + +/// Git 平台类型 +enum GitPlatform { + github( + id: 'github', + name: 'GitHub', + defaultServerUrl: 'https://github.com', + apiBaseUrl: 'https://api.github.com', + brandColor: Color(0xFF24292E), + ), + gitee( + id: 'gitee', + name: 'Gitee', + defaultServerUrl: 'https://gitee.com', + apiBaseUrl: 'https://gitee.com/api/v5', + brandColor: Color(0xFFC71D23), + ), + gitlab( + id: 'gitlab', + name: 'GitLab', + defaultServerUrl: 'https://gitlab.com', + apiBaseUrl: 'https://gitlab.com/api/v4', + brandColor: Color(0xFFFC6D26), + ), + generic( + id: 'generic', + name: '通用 / 自建 Git', + defaultServerUrl: '', + apiBaseUrl: '', + brandColor: Color(0xFF3E4347), + ); + + final String id; + final String name; + final String defaultServerUrl; + final String apiBaseUrl; + final Color brandColor; + + const GitPlatform({ + required this.id, + required this.name, + required this.defaultServerUrl, + required this.apiBaseUrl, + required this.brandColor, + }); + + static GitPlatform fromString(String? val) { + return GitPlatform.values.firstWhere( + (e) => e.id == val || e.name.toLowerCase() == val?.toLowerCase(), + orElse: () => GitPlatform.github, + ); + } +} + +/// 认证凭据类型 +enum GitAuthType { + token('token', 'PAT 个人访问令牌'), + ssh('ssh', 'SSH 密钥对'); + + final String id; + final String label; + const GitAuthType(this.id, this.label); + + static GitAuthType fromString(String? val) { + return GitAuthType.values.firstWhere( + (e) => e.id == val, + orElse: () => GitAuthType.token, + ); + } +} + +/// Git 云端账号模型 +class GitAccount { + final String id; + final GitPlatform platform; + final String username; + final String displayName; + final String email; + final GitAuthType authType; + final String token; + final String? sshKeyId; + final String serverUrl; + final String? avatarUrl; + final bool isDefault; + final DateTime createdAt; + + const GitAccount({ + required this.id, + required this.platform, + required this.username, + this.displayName = '', + this.email = '', + this.authType = GitAuthType.token, + this.token = '', + this.sshKeyId, + required this.serverUrl, + this.avatarUrl, + this.isDefault = false, + required this.createdAt, + }); + + String get effectiveName => displayName.trim().isNotEmpty ? displayName.trim() : username; + + factory GitAccount.fromJson(Map json) { + return GitAccount( + id: json['id'] as String? ?? '', + platform: GitPlatform.fromString(json['platform'] as String?), + username: json['username'] as String? ?? '', + displayName: json['displayName'] as String? ?? '', + email: json['email'] as String? ?? '', + authType: GitAuthType.fromString(json['authType'] as String?), + token: json['token'] as String? ?? '', + sshKeyId: json['sshKeyId'] as String?, + serverUrl: json['serverUrl'] as String? ?? '', + avatarUrl: json['avatarUrl'] as String?, + isDefault: json['isDefault'] as bool? ?? false, + createdAt: json['createdAt'] != null + ? DateTime.tryParse(json['createdAt'].toString()) ?? DateTime.now() + : DateTime.now(), + ); + } + + Map toJson() { + return { + 'id': id, + 'platform': platform.id, + 'username': username, + 'displayName': displayName, + 'email': email, + 'authType': authType.id, + 'token': token, + 'sshKeyId': sshKeyId, + 'serverUrl': serverUrl, + 'avatarUrl': avatarUrl, + 'isDefault': isDefault, + 'createdAt': createdAt.toIso8601String(), + }; + } + + GitAccount copyWith({ + String? id, + GitPlatform? platform, + String? username, + String? displayName, + String? email, + GitAuthType? authType, + String? token, + String? sshKeyId, + String? serverUrl, + String? avatarUrl, + bool? isDefault, + DateTime? createdAt, + }) { + return GitAccount( + id: id ?? this.id, + platform: platform ?? this.platform, + username: username ?? this.username, + displayName: displayName ?? this.displayName, + email: email ?? this.email, + authType: authType ?? this.authType, + token: token ?? this.token, + sshKeyId: sshKeyId ?? this.sshKeyId, + serverUrl: serverUrl ?? this.serverUrl, + avatarUrl: avatarUrl ?? this.avatarUrl, + isDefault: isDefault ?? this.isDefault, + createdAt: createdAt ?? this.createdAt, + ); + } +} diff --git a/lib/models/lsp_language_config.dart b/lib/models/lsp_language_config.dart index 2586913..07cd522 100644 --- a/lib/models/lsp_language_config.dart +++ b/lib/models/lsp_language_config.dart @@ -6,6 +6,8 @@ class LspLanguageConfig { final String serverCommand; final List serverArgs; final String package; + final String? installCommand; + final String? uninstallCommand; final bool enabled; /// 兼容别名 @@ -20,6 +22,8 @@ class LspLanguageConfig { required this.serverCommand, this.serverArgs = const [], required this.package, + this.installCommand, + this.uninstallCommand, this.enabled = true, }); @@ -40,6 +44,8 @@ class LspLanguageConfig { .toList() ?? [], package: pkg, + installCommand: json['installCommand'] as String?, + uninstallCommand: json['uninstallCommand'] as String?, enabled: json['enabled'] as bool? ?? true, ); } @@ -54,6 +60,8 @@ class LspLanguageConfig { 'serverArgs': serverArgs, 'package': package, 'apkPackage': package, + 'installCommand': installCommand, + 'uninstallCommand': uninstallCommand, 'enabled': enabled, }; } @@ -67,6 +75,8 @@ class LspLanguageConfig { List? serverArgs, String? package, String? apkPackage, + String? installCommand, + String? uninstallCommand, bool? enabled, }) { return LspLanguageConfig( @@ -77,30 +87,34 @@ class LspLanguageConfig { serverCommand: serverCommand ?? this.serverCommand, serverArgs: serverArgs ?? this.serverArgs, package: package ?? apkPackage ?? this.package, + installCommand: installCommand ?? this.installCommand, + uninstallCommand: uninstallCommand ?? this.uninstallCommand, enabled: enabled ?? this.enabled, ); } - /// 官方内置语言支持模版(基于 Ubuntu 官方 apt 工具链,仅作探测与安装指引,不默认写入用户配置) + /// 官方内置语言支持模版(基于 Ubuntu 官方 apt 工具链与各语言官方分发渠道,仅作探测与安装指引,不默认写入用户配置) static List get builtinPresets => [ const LspLanguageConfig( id: 'c_cpp', name: 'C / C++', languageId: 'cpp', - fileExtensions: ['.c', '.cpp', '.cc', '.cxx', '.h', '.hpp'], + fileExtensions: ['.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.hxx', '.hh'], serverCommand: 'clangd', serverArgs: ['--background-index'], package: 'clangd', + installCommand: 'apt-get update && apt-get install -y --no-install-recommends clangd', enabled: true, ), const LspLanguageConfig( id: 'python', name: 'Python', languageId: 'python', - fileExtensions: ['.py'], + fileExtensions: ['.py', '.pyw', '.pyi'], serverCommand: 'pylsp', serverArgs: [], package: 'python3-pylsp', + installCommand: 'apt-get update && apt-get install -y --no-install-recommends python3-pylsp', enabled: true, ), const LspLanguageConfig( @@ -111,6 +125,7 @@ class LspLanguageConfig { serverCommand: 'rust-analyzer', serverArgs: [], package: 'rust-analyzer', + installCommand: 'apt-get update && apt-get install -y --no-install-recommends rust-analyzer', enabled: true, ), const LspLanguageConfig( @@ -121,16 +136,19 @@ class LspLanguageConfig { serverCommand: 'gopls', serverArgs: [], package: 'gopls', + installCommand: 'apt-get update && apt-get install -y --no-install-recommends gopls', enabled: true, ), const LspLanguageConfig( id: 'shell', name: 'Shell Script', languageId: 'shellscript', - fileExtensions: ['.sh', '.bash'], + fileExtensions: ['.sh', '.bash', '.zsh', '.ksh'], serverCommand: 'bash-language-server', serverArgs: ['start'], package: 'bash-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm shellcheck shfmt && npm install -g bash-language-server', enabled: true, ), const LspLanguageConfig( @@ -141,16 +159,104 @@ class LspLanguageConfig { serverCommand: 'jdtls', serverArgs: [], package: 'jdtls', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends default-jdk curl tar && mkdir -p /opt/jdtls && curl -sSL https://download.eclipse.org/jdtls/snapshots/jdt-language-server-latest.tar.gz | tar -xz -C /opt/jdtls && ln -sf /opt/jdtls/bin/jdtls /usr/local/bin/jdtls', + enabled: true, + ), + const LspLanguageConfig( + id: 'javascript', + name: 'JavaScript', + languageId: 'javascript', + fileExtensions: ['.js', '.jsx', '.mjs', '.cjs'], + serverCommand: 'typescript-language-server', + serverArgs: ['--stdio'], + package: 'typescript-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g typescript-language-server typescript', enabled: true, ), const LspLanguageConfig( id: 'typescript', name: 'TypeScript', languageId: 'typescript', - fileExtensions: ['.ts', '.mts', '.tsx'], + fileExtensions: ['.ts', '.mts', '.cts', '.tsx'], serverCommand: 'typescript-language-server', serverArgs: ['--stdio'], package: 'typescript-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g typescript-language-server typescript', + enabled: true, + ), + const LspLanguageConfig( + id: 'html', + name: 'HTML', + languageId: 'html', + fileExtensions: ['.html', '.htm', '.xhtml'], + serverCommand: 'vscode-html-language-server', + serverArgs: ['--stdio'], + package: 'vscode-langservers-extracted', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g vscode-langservers-extracted', + enabled: true, + ), + const LspLanguageConfig( + id: 'css', + name: 'CSS / SCSS / LESS', + languageId: 'css', + fileExtensions: ['.css', '.scss', '.less'], + serverCommand: 'vscode-css-language-server', + serverArgs: ['--stdio'], + package: 'vscode-langservers-extracted', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g vscode-langservers-extracted', + enabled: true, + ), + const LspLanguageConfig( + id: 'json', + name: 'JSON', + languageId: 'json', + fileExtensions: ['.json', '.jsonc'], + serverCommand: 'vscode-json-language-server', + serverArgs: ['--stdio'], + package: 'vscode-langservers-extracted', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g vscode-langservers-extracted', + enabled: true, + ), + const LspLanguageConfig( + id: 'yaml', + name: 'YAML', + languageId: 'yaml', + fileExtensions: ['.yaml', '.yml'], + serverCommand: 'yaml-language-server', + serverArgs: ['--stdio'], + package: 'yaml-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g yaml-language-server', + enabled: true, + ), + const LspLanguageConfig( + id: 'markdown', + name: 'Markdown', + languageId: 'markdown', + fileExtensions: ['.md', '.markdown'], + serverCommand: 'vscode-markdown-languageserver', + serverArgs: ['--stdio'], + package: 'vscode-markdown-languageserver', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g vscode-markdown-languageserver', + enabled: true, + ), + const LspLanguageConfig( + id: 'cmake', + name: 'CMake', + languageId: 'cmake', + fileExtensions: ['.cmake', 'CMakeLists.txt'], + serverCommand: 'cmake-language-server', + serverArgs: [], + package: 'cmake-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends python3-pip && pip3 install --break-system-packages cmake-language-server', enabled: true, ), const LspLanguageConfig( @@ -161,6 +267,223 @@ class LspLanguageConfig { serverCommand: 'lua-language-server', serverArgs: [], package: 'lua-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends curl tar gzip && ARCH=\$(dpkg --print-architecture) && if [ "\$ARCH" = "arm64" ]; then LARCH="arm64"; else LARCH="x64"; fi && mkdir -p /opt/lua-language-server && curl -sSL https://github.com/LuaLS/lua-language-server/releases/download/3.13.6/lua-language-server-3.13.6-linux-\$LARCH.tar.gz | tar -xz -C /opt/lua-language-server && ln -sf /opt/lua-language-server/bin/lua-language-server /usr/local/bin/lua-language-server', + enabled: true, + ), + const LspLanguageConfig( + id: 'php', + name: 'PHP', + languageId: 'php', + fileExtensions: ['.php', '.phtml', '.php3', '.php4', '.php5'], + serverCommand: 'intelephense', + serverArgs: ['--stdio'], + package: 'intelephense', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g intelephense', + enabled: true, + ), + const LspLanguageConfig( + id: 'ruby', + name: 'Ruby', + languageId: 'ruby', + fileExtensions: ['.rb', '.rake', '.gemspec'], + serverCommand: 'solargraph', + serverArgs: ['stdio'], + package: 'solargraph', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends ruby ruby-dev build-essential && gem install solargraph', + enabled: true, + ), + const LspLanguageConfig( + id: 'kotlin', + name: 'Kotlin', + languageId: 'kotlin', + fileExtensions: ['.kt', '.kts'], + serverCommand: 'kotlin-language-server', + serverArgs: [], + package: 'kotlin-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends default-jre curl unzip && mkdir -p /opt/kotlin-language-server && curl -sSL https://github.com/fwcd/kotlin-language-server/releases/latest/download/server.zip -o /tmp/kls.zip && unzip -o /tmp/kls.zip -d /opt/kotlin-language-server && ln -sf /opt/kotlin-language-server/bin/kotlin-language-server /usr/local/bin/kotlin-language-server && rm -f /tmp/kls.zip', + enabled: true, + ), + const LspLanguageConfig( + id: 'swift', + name: 'Swift', + languageId: 'swift', + fileExtensions: ['.swift'], + serverCommand: 'sourcekit-lsp', + serverArgs: [], + package: 'sourcekit-lsp', + installCommand: 'echo "Please install swift toolchain containing sourcekit-lsp for your Linux distro."', + enabled: true, + ), + const LspLanguageConfig( + id: 'csharp', + name: 'C#', + languageId: 'csharp', + fileExtensions: ['.cs'], + serverCommand: 'csharp-ls', + serverArgs: [], + package: 'csharp-ls', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends dotnet-sdk-8.0 && dotnet tool install --global csharp-ls && ln -sf /root/.dotnet/tools/csharp-ls /usr/local/bin/csharp-ls', + enabled: true, + ), + const LspLanguageConfig( + id: 'dart', + name: 'Dart', + languageId: 'dart', + fileExtensions: ['.dart'], + serverCommand: 'dart', + serverArgs: ['language-server', '--protocol=lsp'], + package: 'dart', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends apt-transport-https curl gnupg && curl -fsSL https://dl-ssl.google.com/linux/linux_signing_key.pub | gpg --dearmor -o /usr/share/keyrings/dart.gpg --yes && echo "deb [signed-by=/usr/share/keyrings/dart.gpg] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main" > /etc/apt/sources.list.d/dart_stable.list && apt-get update && apt-get install -y dart', + enabled: true, + ), + const LspLanguageConfig( + id: 'sql', + name: 'SQL', + languageId: 'sql', + fileExtensions: ['.sql'], + serverCommand: 'sql-language-server', + serverArgs: ['up', '--method', 'stdio'], + package: 'sql-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g sql-language-server', + enabled: true, + ), + const LspLanguageConfig( + id: 'xml', + name: 'XML', + languageId: 'xml', + fileExtensions: ['.xml', '.svg', '.plist', '.xsd', '.xaml'], + serverCommand: 'lemminx', + serverArgs: [], + package: 'lemminx', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends default-jre curl && ARCH=\$(dpkg --print-architecture) && curl -sSL -o /usr/local/bin/lemminx "https://download.eclipse.org/lemminx/releases/0.27.0/lemminx-linux-\$ARCH" && chmod +x /usr/local/bin/lemminx', + enabled: true, + ), + const LspLanguageConfig( + id: 'dockerfile', + name: 'Dockerfile', + languageId: 'dockerfile', + fileExtensions: ['.dockerfile', 'Dockerfile'], + serverCommand: 'docker-langserver', + serverArgs: ['--stdio'], + package: 'dockerfile-language-server-nodejs', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g dockerfile-language-server-nodejs', + enabled: true, + ), + const LspLanguageConfig( + id: 'toml', + name: 'TOML', + languageId: 'toml', + fileExtensions: ['.toml'], + serverCommand: 'taplo', + serverArgs: ['lsp', 'stdio'], + package: 'taplo', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends curl gzip && ARCH=\$(dpkg --print-architecture) && if [ "\$ARCH" = "arm64" ]; then TARCH="aarch64"; else TARCH="x86_64"; fi && curl -sSL "https://github.com/tamasfe/taplo/releases/download/0.9.3/taplo-full-linux-\$TARCH.gz" | gzip -d > /usr/local/bin/taplo && chmod +x /usr/local/bin/taplo', + enabled: true, + ), + const LspLanguageConfig( + id: 'r', + name: 'R', + languageId: 'r', + fileExtensions: ['.r', '.R'], + serverCommand: 'R', + serverArgs: ['--slave', '-e', 'languageserver::run()'], + package: 'r-base', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends r-base && R -e "install.packages(\'languageserver\', repos=\'https://cloud.r-project.org\')"', + enabled: true, + ), + const LspLanguageConfig( + id: 'perl', + name: 'Perl', + languageId: 'perl', + fileExtensions: ['.pl', '.pm'], + serverCommand: 'perl', + serverArgs: ['-MPerl::LanguageServer', '-e', 'Perl::LanguageServer::run'], + package: 'libperl-languageserver-perl', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends libperl-languageserver-perl', + enabled: true, + ), + const LspLanguageConfig( + id: 'zig', + name: 'Zig', + languageId: 'zig', + fileExtensions: ['.zig'], + serverCommand: 'zls', + serverArgs: [], + package: 'zls', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends curl xz-utils && ARCH=\$(dpkg --print-architecture) && if [ "\$ARCH" = "arm64" ]; then ZARCH="aarch64"; else ZARCH="x86_64"; fi && curl -sSL "https://zigtools.org/zls/downloads/\$ZARCH-linux/bin/zls" -o /usr/local/bin/zls && chmod +x /usr/local/bin/zls', + enabled: true, + ), + const LspLanguageConfig( + id: 'vue', + name: 'Vue', + languageId: 'vue', + fileExtensions: ['.vue'], + serverCommand: 'vue-language-server', + serverArgs: ['--stdio'], + package: '@vue/language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g @vue/language-server typescript', + enabled: true, + ), + const LspLanguageConfig( + id: 'svelte', + name: 'Svelte', + languageId: 'svelte', + fileExtensions: ['.svelte'], + serverCommand: 'svelteserver', + serverArgs: ['--stdio'], + package: 'svelte-language-server', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g svelte-language-server typescript', + enabled: true, + ), + const LspLanguageConfig( + id: 'tex', + name: 'LaTeX', + languageId: 'latex', + fileExtensions: ['.tex', '.latex', '.sty', '.cls'], + serverCommand: 'texlab', + serverArgs: [], + package: 'texlab', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends curl tar gzip && ARCH=\$(dpkg --print-architecture) && if [ "\$ARCH" = "arm64" ]; then TARCH="aarch64"; else TARCH="x86_64"; fi && curl -sSL "https://github.com/latex-lsp/texlab/releases/latest/download/texlab-\$TARCH-linux.tar.gz" | tar -xz -C /usr/local/bin/ && chmod +x /usr/local/bin/texlab', + enabled: true, + ), + const LspLanguageConfig( + id: 'graphql', + name: 'GraphQL', + languageId: 'graphql', + fileExtensions: ['.graphql', '.gql'], + serverCommand: 'graphql-lsp', + serverArgs: ['server', '-m', 'stream'], + package: 'graphql-language-service-cli', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g graphql-language-service-cli', + enabled: true, + ), + const LspLanguageConfig( + id: 'protobuf', + name: 'Protocol Buffers', + languageId: 'proto', + fileExtensions: ['.proto'], + serverCommand: 'bufls', + serverArgs: ['serve'], + package: 'bufls', + installCommand: + 'apt-get update && apt-get install -y --no-install-recommends npm && npm install -g @bufbuild/buf && ln -sf \$(which buf) /usr/local/bin/bufls', enabled: true, ), ]; @@ -168,15 +491,28 @@ class LspLanguageConfig { /// 保持向后兼容别名 static List get defaultPresets => builtinPresets; - /// 根据文件后缀从内置预设模版中匹配支持的语言 - static LspLanguageConfig? findBuiltinByExtension(String ext) { + /// 根据文件后缀或特殊文件名从内置预设模版中匹配支持的语言 + static LspLanguageConfig? findBuiltinByExtension(String ext, {String? filename}) { + final cleanName = filename?.trim().toLowerCase(); + if (cleanName != null && cleanName.isNotEmpty) { + for (final preset in builtinPresets) { + for (final item in preset.fileExtensions) { + if (!item.startsWith('.') && item.toLowerCase() == cleanName) { + return preset; + } + } + } + } + if (ext.isEmpty) return null; final normalized = ext.startsWith('.') ? ext.toLowerCase() : '.$ext'.toLowerCase(); for (final preset in builtinPresets) { for (final item in preset.fileExtensions) { - final itemNorm = item.startsWith('.') ? item.toLowerCase() : '.$item'.toLowerCase(); - if (itemNorm == normalized) { - return preset; + if (item.startsWith('.')) { + final itemNorm = item.toLowerCase(); + if (itemNorm == normalized) { + return preset; + } } } } diff --git a/lib/providers/git_provider.dart b/lib/providers/git_provider.dart index a4337b3..b9094c5 100644 --- a/lib/providers/git_provider.dart +++ b/lib/providers/git_provider.dart @@ -140,6 +140,25 @@ class GitProvider extends ChangeNotifier { } } + /// 响应底层运行容器被销毁重建:立即失效环境缓存,清空内存仓库与分支状态,恢复未安装引导 + void onContainerReset() { + _gitService.invalidateEnvStatus(); + _gitInstalled = false; + _gitVersion = null; + _repositories = []; + _currentRepoPath = null; + _changedFiles = []; + _rebuildStatusMaps(); + _currentBranch = null; + _branches = []; + _tags = []; + _commits = []; + _stashCount = 0; + _errorMessage = '底层容器已重置,需重新安装 Git 工具链'; + _isLoading = false; + notifyListeners(); + } + int _refreshSeq = 0; /// 刷新 Git 状态与仓库信息 diff --git a/lib/services/distro_manager.dart b/lib/services/distro_manager.dart index 23ba0a4..c849af8 100644 --- a/lib/services/distro_manager.dart +++ b/lib/services/distro_manager.dart @@ -130,9 +130,10 @@ class DistroManager { BuildContext? context, required SettingsProvider settings, bool showToast = true, + Directory? customRootDir, }) async { final mode = settings.containerRuntimeMode; - final rootDir = await getSystemRootDir(DistroRepository.defaultSystemName); + final rootDir = customRootDir ?? await getSystemRootDir(DistroRepository.defaultSystemName); ContainerRuntimeType effective = ContainerRuntimeType.proot; diff --git a/lib/services/git_account_service.dart b/lib/services/git_account_service.dart new file mode 100644 index 0000000..17e2fdf --- /dev/null +++ b/lib/services/git_account_service.dart @@ -0,0 +1,480 @@ +import 'dart:convert'; +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 '../models/git_account.dart'; +import 'distro_manager.dart'; +import 'internal_engine_service.dart'; +import 'toolchain_service.dart'; + +/// Git 账号与远程凭据管理服务 +class GitAccountService extends ChangeNotifier { + static final GitAccountService instance = GitAccountService._internal(); + GitAccountService._internal(); + + List _accounts = []; + bool _isLoaded = false; + + List get accounts => List.unmodifiable(_accounts); + bool get isLoaded => _isLoaded; + + /// 测试自定义配置文件目录 + @visibleForTesting + Directory? customBaseDir; + + /// 获取配置文件路径: `/config/git_accounts.json` + Future getConfigFile() async { + final Directory baseDir; + if (customBaseDir != null) { + baseDir = customBaseDir!; + } else { + final appDir = await getApplicationSupportDirectory(); + final rootPath = p.basename(appDir.path) == 'files' + ? appDir.path + : p.join(appDir.path, 'files'); + baseDir = Directory(p.join(rootPath, 'config')); + } + + if (!baseDir.existsSync()) { + baseDir.createSync(recursive: true); + } + return File(p.join(baseDir.path, 'git_accounts.json')); + } + + /// 获取宿主持久化保存 SSH 密钥的目录: `/ssh/` + Future getPersistentSshDir() async { + final Directory sshDir; + if (customBaseDir != null) { + sshDir = Directory(p.join(customBaseDir!.path, 'ssh')); + } else { + final appDir = await getApplicationSupportDirectory(); + final rootPath = p.basename(appDir.path) == 'files' + ? appDir.path + : p.join(appDir.path, 'files'); + sshDir = Directory(p.join(rootPath, 'ssh')); + } + if (!sshDir.existsSync()) { + sshDir.createSync(recursive: true); + } + return sshDir; + } + + /// 加载所有保存的账号 + Future> loadAccounts({bool forceReload = false}) async { + if (_isLoaded && !forceReload) { + return _accounts; + } + + final file = await getConfigFile(); + if (!file.existsSync()) { + _accounts = []; + _isLoaded = true; + notifyListeners(); + return _accounts; + } + + try { + final text = file.readAsStringSync().trim(); + if (text.isNotEmpty) { + final dynamic raw = jsonDecode(text); + if (raw is List) { + _accounts = raw + .map((e) => e is Map ? GitAccount.fromJson(e) : null) + .whereType() + .toList(); + } + } + } catch (e) { + debugPrint('[GitAccountService] 读取账号配置异常: $e'); + _accounts = []; + } + + _isLoaded = true; + notifyListeners(); + return _accounts; + } + + /// 保存并持久化账号列表 + Future _saveToDisk() async { + final file = await getConfigFile(); + final jsonList = _accounts.map((a) => a.toJson()).toList(); + await file.writeAsString(const JsonEncoder.withIndent(' ').convert(jsonList)); + notifyListeners(); + await syncContainerCredentials(); + } + + /// 将所有已保存的账号凭据同步写入容器的 ~/.git-credentials,使容器内终端与 UI 操作均免密生效 + Future syncContainerCredentials() async { + try { + final engine = InternalEngineService.instance; + if (!await engine.isEngineInstalled()) return; + + final rootfs = await engine.getRootfsDir(); + final credFile = File(p.join(rootfs.path, 'root', '.git-credentials')); + final lines = []; + for (final acc in _accounts) { + if (acc.token.isNotEmpty) { + final uri = Uri.tryParse(acc.serverUrl.isNotEmpty ? acc.serverUrl : acc.platform.defaultServerUrl); + final host = uri?.host ?? 'github.com'; + final user = Uri.encodeComponent(acc.username); + final pass = Uri.encodeComponent(acc.token); + lines.add('https://$user:$pass@$host'); + } + } + credFile.parent.createSync(recursive: true); + await credFile.writeAsString(lines.join('\n')); + + // 确保全局开启 credential.helper store + await DistroManager().runHeadlessCommand( + systemName: DistroRepository.defaultSystemName, + customRootDir: rootfs, + command: 'git config --global credential.helper store', + ); + } catch (e) { + debugPrint('[GitAccountService] 同步容器凭据异常: $e'); + } + } + + /// 添加或更新账号 + Future saveAccount(GitAccount account) async { + await loadAccounts(); + final index = _accounts.indexWhere((a) => a.id == account.id); + if (index >= 0) { + _accounts[index] = account; + } else { + // 若这是该平台的第一个账号,默认设为默认 + final samePlatform = _accounts.where((a) => a.platform == account.platform); + if (samePlatform.isEmpty) { + account = account.copyWith(isDefault: true); + } + _accounts.add(account); + } + + if (account.isDefault) { + _setDefaultAccountInternal(account.id, account.platform); + } + + await _saveToDisk(); + } + + /// 删除账号 + Future deleteAccount(String accountId) async { + await loadAccounts(); + _accounts.removeWhere((a) => a.id == accountId); + await _saveToDisk(); + } + + /// 将某账号设为对应平台的默认账号 + Future setDefaultAccount(String accountId) async { + await loadAccounts(); + final account = _accounts.where((a) => a.id == accountId).firstOrNull; + if (account == null) return; + _setDefaultAccountInternal(accountId, account.platform); + await _saveToDisk(); + } + + void _setDefaultAccountInternal(String targetId, GitPlatform platform) { + for (int i = 0; i < _accounts.length; i++) { + if (_accounts[i].platform == platform) { + _accounts[i] = _accounts[i].copyWith(isDefault: _accounts[i].id == targetId); + } + } + } + + /// 根据远程 URL 自动匹配最合适的账号(优先匹配 Host 与默认账号) + GitAccount? findAccountForUrl(String remoteUrl) { + if (_accounts.isEmpty) return null; + final cleanUrl = remoteUrl.trim().toLowerCase(); + + if (cleanUrl.contains('github.com')) { + return _accounts.firstWhere( + (a) => a.platform == GitPlatform.github && a.isDefault, + orElse: () => _accounts.firstWhere( + (a) => a.platform == GitPlatform.github, + orElse: () => _accounts.first, + ), + ); + } + + if (cleanUrl.contains('gitee.com')) { + return _accounts.firstWhere( + (a) => a.platform == GitPlatform.gitee && a.isDefault, + orElse: () => _accounts.firstWhere( + (a) => a.platform == GitPlatform.gitee, + orElse: () => _accounts.first, + ), + ); + } + + if (cleanUrl.contains('gitlab')) { + return _accounts.firstWhere( + (a) => a.platform == GitPlatform.gitlab && a.isDefault, + orElse: () => _accounts.firstWhere( + (a) => a.platform == GitPlatform.gitlab, + orElse: () => _accounts.first, + ), + ); + } + + // 通用自建 Git 匹配 serverUrl 域名 + for (final acc in _accounts) { + if (acc.serverUrl.isNotEmpty) { + final host = Uri.tryParse(acc.serverUrl)?.host.toLowerCase(); + if (host != null && host.isNotEmpty && cleanUrl.contains(host)) { + return acc; + } + } + } + + return _accounts.where((a) => a.isDefault).firstOrNull ?? _accounts.firstOrNull; + } + + /// 验证 Token 并从平台获取真实用户信息(用户名、邮箱、头像等) + Future<({bool success, String? username, String? displayName, String? email, String? avatarUrl, String? error})> + verifyTokenAndFetchUserInfo( + GitPlatform platform, + String token, { + String? customServerUrl, + }) async { + final cleanToken = token.trim(); + if (cleanToken.isEmpty) { + return ( + success: false, + username: null, + displayName: null, + email: null, + avatarUrl: null, + error: '令牌不能为空' + ); + } + + final client = HttpClient(); + client.connectionTimeout = const Duration(seconds: 12); + + try { + final Uri targetUri; + final Map headers = { + 'User-Agent': 'CodeEditorApp-Mobile/1.0', + 'Accept': 'application/json', + }; + + switch (platform) { + case GitPlatform.github: + targetUri = Uri.parse('${GitPlatform.github.apiBaseUrl}/user'); + headers['Authorization'] = 'Bearer $cleanToken'; + headers['Accept'] = 'application/vnd.github+json'; + break; + + case GitPlatform.gitee: + targetUri = Uri.parse('${GitPlatform.gitee.apiBaseUrl}/user?access_token=$cleanToken'); + break; + + case GitPlatform.gitlab: + case GitPlatform.generic: + final base = (customServerUrl != null && customServerUrl.trim().isNotEmpty) + ? customServerUrl.trim().replaceAll(RegExp(r'/+$'), '') + : GitPlatform.gitlab.defaultServerUrl; + targetUri = Uri.parse('$base/api/v4/user'); + headers['PRIVATE-TOKEN'] = cleanToken; + break; + } + + final request = await client.getUrl(targetUri); + headers.forEach((k, v) => request.headers.set(k, v)); + final response = await request.close(); + + final body = await response.transform(utf8.decoder).join(); + if (response.statusCode >= 200 && response.statusCode < 300) { + final dynamic data = jsonDecode(body); + if (data is Map) { + final username = (data['login'] ?? data['username'] ?? '').toString(); + final displayName = (data['name'] ?? username).toString(); + final email = (data['email'] ?? '').toString(); + final avatarUrl = (data['avatar_url'] ?? data['avatarUrl'] ?? '').toString(); + return ( + success: true, + username: username.isNotEmpty ? username : displayName, + displayName: displayName, + email: email, + avatarUrl: avatarUrl.isNotEmpty ? avatarUrl : null, + error: null, + ); + } + } + + final dynamic errJson = jsonDecode(body); + final errMsg = errJson is Map ? (errJson['message'] ?? errJson['error_description'] ?? body) : body; + return ( + success: false, + username: null, + displayName: null, + email: null, + avatarUrl: null, + error: '验证失败 (${response.statusCode}): $errMsg', + ); + } catch (e) { + debugPrint('[GitAccountService] 验证 Token 网络异常: $e'); + return ( + success: false, + username: null, + displayName: null, + email: null, + avatarUrl: null, + error: '网络连接异常: $e', + ); + } finally { + client.close(); + } + } + + /// 备份容器内的 SSH 密钥至宿主持久化目录,防止容器重置/重建丢失 + Future _backupSshKeysToHost(Directory rootfs) async { + try { + final sshDir = await getPersistentSshDir(); + final privFile = File(p.join(rootfs.path, 'root', '.ssh', 'id_ed25519')); + final pubFile = File(p.join(rootfs.path, 'root', '.ssh', 'id_ed25519.pub')); + + if (privFile.existsSync()) { + privFile.copySync(p.join(sshDir.path, 'id_ed25519')); + } + if (pubFile.existsSync()) { + pubFile.copySync(p.join(sshDir.path, 'id_ed25519.pub')); + } + } catch (e) { + debugPrint('[GitAccountService] 备份 SSH 密钥到宿主异常: $e'); + } + } + + /// 当容器重建时,将宿主持久化目录的 SSH 密钥还原至容器内 + Future _restoreSshKeysToContainer(Directory rootfs, Directory hostSshDir) async { + try { + final containerSshDir = Directory(p.join(rootfs.path, 'root', '.ssh')); + if (!containerSshDir.existsSync()) { + containerSshDir.createSync(recursive: true); + } + + final hostPriv = File(p.join(hostSshDir.path, 'id_ed25519')); + final hostPub = File(p.join(hostSshDir.path, 'id_ed25519.pub')); + + if (hostPriv.existsSync()) { + hostPriv.copySync(p.join(containerSshDir.path, 'id_ed25519')); + } + if (hostPub.existsSync()) { + hostPub.copySync(p.join(containerSshDir.path, 'id_ed25519.pub')); + } + + // 修复容器内文件权限(私钥 600,公钥 644,目录 700) + await DistroManager().runHeadlessCommand( + systemName: DistroRepository.defaultSystemName, + customRootDir: rootfs, + command: 'chmod 700 /root/.ssh 2>/dev/null; chmod 600 /root/.ssh/id_ed25519 2>/dev/null; chmod 644 /root/.ssh/id_ed25519.pub 2>/dev/null || true', + timeout: const Duration(seconds: 10), + ); + return true; + } catch (e) { + debugPrint('[GitAccountService] 还原 SSH 密钥至容器异常: $e'); + return false; + } + } + + /// 读取 SSH 公钥内容(若容器重建,自动从宿主持久化目录恢复) + Future getSshPublicKey() async { + try { + final sshDir = await getPersistentSshDir(); + final hostPubFile = File(p.join(sshDir.path, 'id_ed25519.pub')); + + final engine = InternalEngineService.instance; + if (await engine.isEngineInstalled()) { + final rootfs = await engine.getRootfsDir(); + final containerSshDir = Directory(p.join(rootfs.path, 'root', '.ssh')); + final containerPubFile = File(p.join(containerSshDir.path, 'id_ed25519.pub')); + + // 1. 若容器内已存在公钥,返回公钥,并确保宿主已备份 + if (containerPubFile.existsSync()) { + final content = containerPubFile.readAsStringSync().trim(); + if (!hostPubFile.existsSync() && content.isNotEmpty) { + await _backupSshKeysToHost(rootfs); + } + return content; + } + + // 2. 若容器被重置/重建(容器内无密钥),但宿主持久化目录存有备份,自动还原进容器! + if (hostPubFile.existsSync()) { + await _restoreSshKeysToContainer(rootfs, sshDir); + return hostPubFile.readAsStringSync().trim(); + } + + // 尝试 rsa + final rsaPubFile = File(p.join(containerSshDir.path, 'id_rsa.pub')); + if (rsaPubFile.existsSync()) { + return rsaPubFile.readAsStringSync().trim(); + } + } + + // 3. 若容器未安装或未运行,宿主持久化目录若有公钥,直接返回展示 + if (hostPubFile.existsSync()) { + return hostPubFile.readAsStringSync().trim(); + } + + return null; + } catch (e) { + debugPrint('[GitAccountService] 获取 SSH 公钥异常: $e'); + return null; + } + } + + /// 在容器内一键生成 Ed25519 SSH 密钥对(生成后自动持久化备份到宿主目录) + Future<({bool success, String? publicKey, String? error})> generateSshKeyPair({String? email}) async { + try { + final engine = InternalEngineService.instance; + if (!await engine.isEngineInstalled()) { + return (success: false, publicKey: null, error: '内置运行容器未安装'); + } + + final rootfs = await engine.getRootfsDir(); + final comment = email?.trim().isNotEmpty == true ? email!.trim() : 'code-editor-mobile'; + final cmd = ''' +${ToolchainService.dpkgAutoHealPrefix} +if ! command -v ssh-keygen >/dev/null 2>&1; then + apt-get update -qq && apt-get install -y --no-install-recommends openssh-client +fi +if ! command -v ssh-keygen >/dev/null 2>&1; then + echo "未找到 ssh-keygen 命令,自动安装 openssh-client 失败,请检查网络后重试" >&2 + exit 1 +fi +mkdir -p /root/.ssh && chmod 700 /root/.ssh +rm -f /root/.ssh/id_ed25519 /root/.ssh/id_ed25519.pub +ssh-keygen -t ed25519 -N "" -C "$comment" -f /root/.ssh/id_ed25519 +chmod 600 /root/.ssh/id_ed25519 +cat /root/.ssh/id_ed25519.pub +'''; + + final res = await DistroManager().runHeadlessCommand( + systemName: DistroRepository.defaultSystemName, + customRootDir: rootfs, + command: cmd, + timeout: const Duration(seconds: 120), + ); + + if (res != null && res.exitCode == 0) { + // 同步备份至宿主持久化目录,确保容器重置时不会丢失 + await _backupSshKeysToHost(rootfs); + final pubKey = await getSshPublicKey(); + return (success: true, publicKey: pubKey, error: null); + } else { + final errText = res?.stderr.toString().trim(); + final outText = res?.stdout.toString().trim(); + final errMsg = (errText != null && errText.isNotEmpty) + ? errText + : ((outText != null && outText.isNotEmpty) ? outText : '生成 SSH 密钥失败'); + return (success: false, publicKey: null, error: errMsg); + } + } catch (e) { + debugPrint('[GitAccountService] 生成 SSH 密钥异常: $e'); + return (success: false, publicKey: null, error: e.toString()); + } + } +} diff --git a/lib/services/git_service.dart b/lib/services/git_service.dart index cf4e4d0..c67b53d 100644 --- a/lib/services/git_service.dart +++ b/lib/services/git_service.dart @@ -37,6 +37,11 @@ class GitService { /// 缓存的 Git 环境可用状态 GitEnvironmentStatus? _cachedEnvStatus; + /// 清除 Git 运行环境检测缓存(在容器重置、重装或安装 Git 后调用) + void invalidateEnvStatus() { + _cachedEnvStatus = null; + } + /// 重置测试环境状态与进程注入 void resetForTesting() { processRunner = null; @@ -362,7 +367,10 @@ class GitService { // 2. 内置引擎环境安装 (Ubuntu PRoot) final engine = InternalEngineService.instance; if (await engine.isEngineInstalled()) { - final success = await engine.installPackage('git', onOutput: onProgress); + final success = await engine.installPackage( + 'apt-get update && apt-get install -y git openssh-client', + onOutput: onProgress, + ); if (success) { _cachedEnvStatus = null; final env = await checkGitInstalled(forceRefresh: true); diff --git a/lib/services/internal_engine_service.dart b/lib/services/internal_engine_service.dart index 5382f97..00bb2b6 100644 --- a/lib/services/internal_engine_service.dart +++ b/lib/services/internal_engine_service.dart @@ -13,6 +13,11 @@ import 'distro_installer.dart'; import 'distro_manager.dart'; import 'lsp/lsp_manager.dart'; import 'toolchain_service.dart'; +import '../models/lsp_language_config.dart'; +import '../providers/git_provider.dart'; +import 'git_service.dart'; +import 'lsp_config_service.dart'; +import '../views/main_view.dart'; /// 代码智能与运行时引擎服务(基于统一主系统 Ubuntu 24.04) class InternalEngineService extends ChangeNotifier { @@ -96,17 +101,27 @@ class InternalEngineService extends ChangeNotifier { notifyListeners(); TerminalProvider? terminalProvider; + GitProvider? gitProvider; try { terminalProvider = Provider.of(context, listen: false); } catch (_) {} + try { + gitProvider = Provider.of(context, listen: false); + } catch (_) {} try { - // 1. 关闭所有运行中的后台语言服务会话 + // 1. 关闭所有运行中的后台语言服务会话,清空已安装的补全组件列表,并重置弹窗提示防打扰记录 await LspManager.instance.disposeAll(); + await LspConfigService.instance.saveConfigs([]); + MainView.clearPromptedLanguage(null); // 2. 清理终端中属于 ubuntu 的活跃会话 terminalProvider?.removeSessionsForDistro(DistroRepository.defaultSystemName); + // 3. 重置 Git 环境可用状态并清理 Git 内存缓存与页面状态 + GitService.instance.invalidateEnvStatus(); + gitProvider?.onContainerReset(); + // 3. 保护 .l2s 目录,避免外部工程中已建立的 PRoot 硬链接替身文件随容器重装被误删 Directory? preservedL2s; try { @@ -180,6 +195,11 @@ class InternalEngineService extends ChangeNotifier { } } + if (success) { + // 重建完成后触发 Git 状态探测刷新(若打开了项目,将自动识别到新容器尚未安装 Git 并呈现引导界面) + gitProvider?.refresh(); + } + _isChecking = false; notifyListeners(); return success; @@ -231,7 +251,7 @@ class InternalEngineService extends ChangeNotifier { } } - /// 在 Ubuntu 系统中安装指定 apt 软件包 + /// 在 Ubuntu 系统中安装指定软件包或执行安装命令 Future installPackage( String packageName, { void Function(String chunk)? onOutput, @@ -242,10 +262,16 @@ class InternalEngineService extends ChangeNotifier { try { final rootfs = await getRootfsDir(); - final installCmd = - '${ToolchainService.dpkgAutoHealPrefix} ' - 'apt-get update && ' - 'apt-get install -y --no-install-recommends ${packageName.trim()}'; + final trimmed = packageName.trim(); + final String installCmd; + if (trimmed.contains(' ') || trimmed.contains('&&') || trimmed.contains('|')) { + installCmd = '${ToolchainService.dpkgAutoHealPrefix} $trimmed'; + } else { + installCmd = + '${ToolchainService.dpkgAutoHealPrefix} ' + 'apt-get update && ' + 'apt-get install -y --no-install-recommends $trimmed'; + } final res = await DistroManager().runHeadlessCommand( systemName: DistroRepository.defaultSystemName, @@ -261,6 +287,18 @@ class InternalEngineService extends ChangeNotifier { } } + /// 针对 LSP 组件安装(优先执行完整 installCommand,若未定义则安装指定 package) + Future installLspConfig( + LspLanguageConfig config, { + void Function(String chunk)? onOutput, + }) async { + final cmd = config.installCommand?.trim(); + if (cmd != null && cmd.isNotEmpty) { + return installPackage(cmd, onOutput: onOutput); + } + return installPackage(config.package, onOutput: onOutput); + } + /// 自动诊断与修复 dpkg 锁及半安装 (reinstreq/half-installed) 死锁状态 Future repairDpkgStatus({void Function(String chunk)? onOutput}) async { if (!await isEngineInstalled()) return false; @@ -331,7 +369,10 @@ fi final uninstallCmd = ''' ${ToolchainService.dpkgAutoHealPrefix} $killSection -apt-get remove --purge -y $targetsToPurge +npm uninstall -g $cleanPkg 2>/dev/null || true +pip uninstall -y $cleanPkg 2>/dev/null || true +gem uninstall -a -x $cleanPkg 2>/dev/null || true +apt-get remove --purge -y $targetsToPurge 2>/dev/null || true apt-get autoremove --purge -y $cmdCleanupSection '''; diff --git a/lib/services/lsp/lsp_manager.dart b/lib/services/lsp/lsp_manager.dart index 6ab44d7..419ea09 100644 --- a/lib/services/lsp/lsp_manager.dart +++ b/lib/services/lsp/lsp_manager.dart @@ -20,9 +20,10 @@ class LspManager extends ChangeNotifier { /// 获取或拉起匹配当前文件的语言服务会话 Future getOrCreateSession(String filePath, {String? workspaceRoot}) async { final ext = p.extension(filePath); - if (ext.isEmpty) return null; + final filename = p.basename(filePath); + if (ext.isEmpty && filename.isEmpty) return null; - final config = LspConfigService.instance.findByExtension(ext); + final config = LspConfigService.instance.findByExtension(ext, filename: filename); if (config == null || !config.enabled) return null; // 检查是否已有存活会话 @@ -134,8 +135,9 @@ class LspManager extends ChangeNotifier { /// 获取当前已存活的会话(不触发异步拉起) LspSession? getExistingSession(String filePath) { final ext = p.extension(filePath); - if (ext.isEmpty) return null; - final config = LspConfigService.instance.findByExtension(ext); + final filename = p.basename(filePath); + if (ext.isEmpty && filename.isEmpty) return null; + final config = LspConfigService.instance.findByExtension(ext, filename: filename); if (config == null) return null; final session = _activeSessions[config.id]; if (session != null && !session.client.isClosed) { diff --git a/lib/services/lsp_config_service.dart b/lib/services/lsp_config_service.dart index 47155d7..28f0617 100644 --- a/lib/services/lsp_config_service.dart +++ b/lib/services/lsp_config_service.dart @@ -140,16 +140,29 @@ class LspConfigService extends ChangeNotifier { notifyListeners(); } - /// 根据文件扩展名查找匹配的已启用语言配置 - LspLanguageConfig? findByExtension(String ext) { + /// 根据文件扩展名或特殊文件名查找匹配的已启用语言配置 + LspLanguageConfig? findByExtension(String ext, {String? filename}) { + final cleanName = filename?.trim().toLowerCase(); + if (cleanName != null && cleanName.isNotEmpty) { + for (final config in _configs) { + for (final item in config.fileExtensions) { + if (!item.startsWith('.') && item.toLowerCase() == cleanName) { + return config.enabled ? config : null; + } + } + } + } + if (ext.isEmpty) return null; final normalized = ext.startsWith('.') ? ext.toLowerCase() : '.$ext'.toLowerCase(); for (final config in _configs) { for (final item in config.fileExtensions) { - final itemNorm = item.startsWith('.') ? item.toLowerCase() : '.$item'.toLowerCase(); - if (itemNorm == normalized) { - return config.enabled ? config : null; + if (item.startsWith('.')) { + final itemNorm = item.toLowerCase(); + if (itemNorm == normalized) { + return config.enabled ? config : null; + } } } } diff --git a/lib/services/toolchain_service.dart b/lib/services/toolchain_service.dart index 3ee209d..bce1768 100644 --- a/lib/services/toolchain_service.dart +++ b/lib/services/toolchain_service.dart @@ -52,7 +52,7 @@ class ToolchainService { 'git': ToolchainRequirement( checkBinary: 'git', displayName: 'Git 版本控制工具', - installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y git', + installCommand: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y git openssh-client', ), 'make': ToolchainRequirement( checkBinary: 'make', diff --git a/lib/views/code_completion_management_view.dart b/lib/views/code_completion_management_view.dart index 2ea05d1..5cecb9a 100644 --- a/lib/views/code_completion_management_view.dart +++ b/lib/views/code_completion_management_view.dart @@ -105,12 +105,12 @@ class _CodeCompletionManagementViewState final l10n = AppLocalizations.of(context); if (l10n == null) return; - final hasPkg = newConfig.package.trim().isNotEmpty; + final hasPkg = newConfig.package.trim().isNotEmpty || (newConfig.installCommand?.trim().isNotEmpty ?? false); if (hasPkg) { final success = await DialogUtils.showSyncLoadingDialog( context, - message: l10n.installingComponent(newConfig.package), - task: () => InternalEngineService.instance.installPackage(newConfig.package), + message: l10n.installingComponent(newConfig.name), + task: () => InternalEngineService.instance.installLspConfig(newConfig), ); if (!mounted) return; diff --git a/lib/views/git_account_management_view.dart b/lib/views/git_account_management_view.dart new file mode 100644 index 0000000..7f40fa5 --- /dev/null +++ b/lib/views/git_account_management_view.dart @@ -0,0 +1,815 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../l10n/app_localizations.dart'; +import '../models/git_account.dart'; +import '../services/git_account_service.dart'; +import '../utils/dialog_utils.dart'; + +/// Git 账号与云端凭据管理视图 +class GitAccountManagementView extends StatefulWidget { + const GitAccountManagementView({super.key}); + + @override + State createState() => _GitAccountManagementViewState(); +} + +class _GitAccountManagementViewState extends State with SingleTickerProviderStateMixin { + final GitAccountService _accountService = GitAccountService.instance; + late TabController _tabController; + bool _isLoading = false; + String? _sshPublicKey; + bool _isGeneratingSsh = false; + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 2, vsync: this); + _loadData(); + } + + Future _loadData() async { + setState(() => _isLoading = true); + await _accountService.loadAccounts(); + final pubKey = await _accountService.getSshPublicKey(); + if (mounted) { + setState(() { + _sshPublicKey = pubKey; + _isLoading = false; + }); + } + } + + @override + void dispose() { + _tabController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l10n = AppLocalizations.of(context)!; + + return Scaffold( + appBar: AppBar( + title: Text(l10n.gitAccountManagement, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18)), + bottom: TabBar( + controller: _tabController, + tabs: [ + Tab(icon: const Icon(Icons.account_box_outlined, size: 20), text: l10n.gitHostedAccounts), + Tab(icon: const Icon(Icons.key_outlined, size: 20), text: l10n.gitSshKeys), + ], + ), + actions: [ + IconButton( + icon: const Icon(Icons.add), + tooltip: l10n.gitAddAccount, + onPressed: () => _openAddAccountDialog(context, l10n), + ), + ], + ), + body: _isLoading + ? const Center(child: CircularProgressIndicator()) + : TabBarView( + controller: _tabController, + children: [ + _buildAccountsTab(context, theme, l10n), + _buildSshKeysTab(context, theme, l10n), + ], + ), + ); + } + + Widget _buildAccountsTab(BuildContext context, ThemeData theme, AppLocalizations l10n) { + return AnimatedBuilder( + animation: _accountService, + builder: (context, _) { + final accounts = _accountService.accounts; + if (accounts.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(32.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer.withValues(alpha: 0.4), + shape: BoxShape.circle, + ), + child: Icon(Icons.cloud_sync_outlined, size: 48, color: theme.colorScheme.primary), + ), + const SizedBox(height: 20), + Text( + l10n.gitNoAccountsTitle, + style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), + ), + ], + ), + ), + ); + } + + return ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + itemCount: accounts.length, + itemBuilder: (context, index) { + final acc = accounts[index]; + return _buildAccountCard(context, theme, l10n, acc); + }, + ); + }, + ); + } + + Widget _buildAccountCard(BuildContext context, ThemeData theme, AppLocalizations l10n, GitAccount account) { + final colorScheme = theme.colorScheme; + final platformDisplayName = account.platform == GitPlatform.generic ? l10n.gitPlatformGeneric : account.platform.name; + + return Card( + margin: const EdgeInsets.only(bottom: 12), + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: account.isDefault ? colorScheme.primary : colorScheme.outlineVariant.withValues(alpha: 0.6), + width: account.isDefault ? 1.6 : 1.0, + ), + ), + child: Padding( + padding: const EdgeInsets.all(14.0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 头像或平台徽标 + Stack( + clipBehavior: Clip.none, + children: [ + CircleAvatar( + radius: 22, + backgroundColor: colorScheme.surfaceContainerHighest, + backgroundImage: account.avatarUrl != null ? NetworkImage(account.avatarUrl!) : null, + child: account.avatarUrl == null + ? Icon(_getPlatformIcon(account.platform), color: account.platform.brandColor) + : null, + ), + Positioned( + right: -4, + bottom: -4, + child: Container( + padding: const EdgeInsets.all(3), + decoration: BoxDecoration( + color: account.platform.brandColor, + shape: BoxShape.circle, + border: Border.all(color: colorScheme.surface, width: 1.5), + ), + child: Icon(_getPlatformIcon(account.platform), size: 10, color: Colors.white), + ), + ), + ], + ), + const SizedBox(width: 14), + + // 账号主体详情 + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Flexible( + child: Text( + account.effectiveName, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15), + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 6), + if (account.isDefault) + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: colorScheme.primaryContainer, + borderRadius: BorderRadius.circular(4), + ), + child: Text( + l10n.gitDefaultAccountBadge, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: colorScheme.onPrimaryContainer, + ), + ), + ), + ], + ), + const SizedBox(height: 2), + Text( + '$platformDisplayName${account.email.isNotEmpty ? ' · ${account.email}' : ''}', + style: TextStyle(fontSize: 12, color: colorScheme.onSurfaceVariant), + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + Row( + children: [ + Icon( + account.authType == GitAuthType.token ? Icons.token_outlined : Icons.key_outlined, + size: 13, + color: colorScheme.outline, + ), + const SizedBox(width: 4), + Flexible( + child: Text( + account.authType == GitAuthType.token ? l10n.gitAuthTypeToken : l10n.gitAuthTypeSsh, + style: TextStyle(fontSize: 11, color: colorScheme.outline), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ], + ), + ), + + // 快捷操作菜单 + PopupMenuButton( + icon: const Icon(Icons.more_vert, size: 20), + onSelected: (val) async { + switch (val) { + case 'default': + await _accountService.setDefaultAccount(account.id); + if (context.mounted) { + DialogUtils.showToast(context, l10n.gitSetAsDefaultSuccess, type: ToastType.success); + } + break; + case 'test': + _testAccountConnection(context, l10n, account); + break; + case 'edit': + _openAddAccountDialog(context, l10n, editingAccount: account); + break; + case 'delete': + _confirmDeleteAccount(context, l10n, account); + break; + } + }, + itemBuilder: (ctx) => [ + if (!account.isDefault) + PopupMenuItem(value: 'default', child: Text(l10n.gitSetAsDefault)), + PopupMenuItem(value: 'test', child: Text(l10n.gitTestConnection)), + PopupMenuItem(value: 'edit', child: Text(l10n.gitEdit)), + PopupMenuItem( + value: 'delete', + child: Text(l10n.delete, style: const TextStyle(color: Colors.red)), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _buildSshKeysTab(BuildContext context, ThemeData theme, AppLocalizations l10n) { + final colorScheme = theme.colorScheme; + + return SingleChildScrollView( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Card( + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.6)), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.vpn_key_rounded, color: colorScheme.primary, size: 22), + const SizedBox(width: 10), + Text( + l10n.gitContainerSshTitle, + style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold), + ), + ], + ), + const SizedBox(height: 16), + + if (_sshPublicKey != null && _sshPublicKey!.isNotEmpty) ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(8), + ), + child: SelectableText( + _sshPublicKey!, + style: const TextStyle(fontFamily: 'JetBrains Mono', fontSize: 11), + ), + ), + const SizedBox(height: 14), + Row( + children: [ + Expanded( + child: FilledButton.icon( + icon: const Icon(Icons.copy_rounded, size: 16), + label: Text(l10n.gitCopyPublicKey), + onPressed: () { + Clipboard.setData(ClipboardData(text: _sshPublicKey!)); + DialogUtils.showToast(context, l10n.gitPublicKeyCopied, type: ToastType.success); + }, + ), + ), + const SizedBox(width: 10), + OutlinedButton( + onPressed: _isGeneratingSsh ? null : () => _confirmRegenerateSsh(context, l10n), + child: _isGeneratingSsh + ? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)) + : Text(l10n.gitRegenerateKey), + ), + ], + ), + ] else ...[ + FilledButton.icon( + icon: _isGeneratingSsh + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), + ) + : const Icon(Icons.add_circle_outline, size: 18), + label: Text(l10n.gitGenerateEd25519Key), + onPressed: _isGeneratingSsh ? null : () => _generateSshKey(l10n), + ), + ], + ], + ), + ), + ), + + const SizedBox(height: 16), + + // 使用指导步骤 Card + Card( + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: colorScheme.outlineVariant.withValues(alpha: 0.6)), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.gitSshGuideTitle, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + const SizedBox(height: 10), + _buildGuideStep('1', l10n.gitSshGuideStep1), + _buildGuideStep('2', l10n.gitSshGuideStep2), + _buildGuideStep('3', l10n.gitSshGuideStep3), + ], + ), + ), + ), + ], + ), + ); + } + + Widget _buildGuideStep(String num, String text) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CircleAvatar( + radius: 9, + child: Text(num, style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold)), + ), + const SizedBox(width: 8), + Expanded(child: Text(text, style: const TextStyle(fontSize: 12))), + ], + ), + ); + } + + IconData _getPlatformIcon(GitPlatform platform) { + switch (platform) { + case GitPlatform.github: + return Icons.code_rounded; + case GitPlatform.gitee: + return Icons.hub_rounded; + case GitPlatform.gitlab: + return Icons.commit_rounded; + case GitPlatform.generic: + return Icons.dns_rounded; + } + } + + Future _generateSshKey(AppLocalizations l10n) async { + final nav = Navigator.of(context, rootNavigator: true); + showDialog( + context: context, + barrierDismissible: false, + builder: (ctx) => AlertDialog( + content: Row( + children: [ + const SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2.5)), + const SizedBox(width: 16), + Expanded(child: Text(l10n.gitGeneratingSshKey)), + ], + ), + ), + ); + + setState(() => _isGeneratingSsh = true); + final res = await _accountService.generateSshKeyPair(); + + if (nav.mounted) nav.pop(); + + if (mounted) { + setState(() { + _isGeneratingSsh = false; + if (res.success) { + _sshPublicKey = res.publicKey; + } + }); + if (res.success) { + DialogUtils.showToast(context, l10n.gitSshKeyGenerateSuccess, type: ToastType.success); + } else { + DialogUtils.showToast(context, res.error ?? l10n.gitSshKeyGenerateFailed, type: ToastType.error); + } + } + } + + Future _confirmRegenerateSsh(BuildContext context, AppLocalizations l10n) async { + final confirm = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text(l10n.gitRegenerateSshConfirmTitle), + content: Text(l10n.gitRegenerateSshConfirmMessage), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l10n.cancel)), + FilledButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l10n.gitOverwrite)), + ], + ), + ); + if (confirm == true) { + _generateSshKey(l10n); + } + } + + Future _testAccountConnection(BuildContext context, AppLocalizations l10n, GitAccount account) async { + final nav = Navigator.of(context, rootNavigator: true); + showDialog( + context: context, + barrierDismissible: false, + builder: (ctx) => AlertDialog( + content: Row( + children: [ + const SizedBox(width: 24, height: 24, child: CircularProgressIndicator(strokeWidth: 2.5)), + const SizedBox(width: 16), + Text(l10n.gitTestingConnection), + ], + ), + ), + ); + + final res = await _accountService.verifyTokenAndFetchUserInfo( + account.platform, + account.token, + customServerUrl: account.serverUrl, + ); + + if (nav.mounted) nav.pop(); + + if (context.mounted) { + if (res.success) { + DialogUtils.showToast( + context, + l10n.gitTestConnectionSuccess(res.username ?? account.username), + type: ToastType.success, + ); + } else { + DialogUtils.showToast( + context, + res.error ?? l10n.gitTestConnectionFailed, + type: ToastType.error, + ); + } + } + } + + Future _confirmDeleteAccount(BuildContext context, AppLocalizations l10n, GitAccount account) async { + final confirm = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text(l10n.gitDeleteAccountConfirmTitle(account.effectiveName)), + content: Text(l10n.gitDeleteAccountConfirmMessage), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l10n.cancel)), + FilledButton( + style: FilledButton.styleFrom(backgroundColor: Colors.red), + onPressed: () => Navigator.pop(ctx, true), + child: Text(l10n.delete), + ), + ], + ), + ); + if (confirm == true) { + await _accountService.deleteAccount(account.id); + if (context.mounted) { + DialogUtils.showToast(context, l10n.gitDeleteAccountSuccess, type: ToastType.success); + } + } + } + + Future _openAddAccountDialog(BuildContext context, AppLocalizations l10n, {GitAccount? editingAccount}) async { + final res = await showDialog( + context: context, + builder: (ctx) => _AddOrEditAccountDialog(editingAccount: editingAccount), + ); + + if (res != null) { + await _accountService.saveAccount(res); + if (context.mounted) { + DialogUtils.showToast(context, editingAccount != null ? l10n.gitAccountUpdatedSuccess : l10n.gitAccountSavedSuccess, type: ToastType.success); + } + } + } +} + +/// 添加或编辑账号弹窗 +class _AddOrEditAccountDialog extends StatefulWidget { + final GitAccount? editingAccount; + + const _AddOrEditAccountDialog({this.editingAccount}); + + @override + State<_AddOrEditAccountDialog> createState() => _AddOrEditAccountDialogState(); +} + +class _AddOrEditAccountDialogState extends State<_AddOrEditAccountDialog> { + late GitPlatform _platform; + late TextEditingController _usernameCtrl; + late TextEditingController _tokenCtrl; + late TextEditingController _serverUrlCtrl; + late TextEditingController _emailCtrl; + bool _isVerifying = false; + String? _verifyError; + + @override + void initState() { + super.initState(); + final acc = widget.editingAccount; + _platform = acc?.platform ?? GitPlatform.github; + _usernameCtrl = TextEditingController(text: acc?.username ?? ''); + _tokenCtrl = TextEditingController(text: acc?.token ?? ''); + _serverUrlCtrl = TextEditingController(text: acc?.serverUrl ?? ''); + _emailCtrl = TextEditingController(text: acc?.email ?? ''); + } + + @override + void dispose() { + _usernameCtrl.dispose(); + _tokenCtrl.dispose(); + _serverUrlCtrl.dispose(); + _emailCtrl.dispose(); + super.dispose(); + } + + Future _openTokenUrl(BuildContext context, AppLocalizations l10n) async { + final String urlStr; + switch (_platform) { + case GitPlatform.github: + urlStr = 'https://github.com/settings/tokens/new?scopes=repo,read:user,user:email'; + break; + case GitPlatform.gitee: + urlStr = 'https://gitee.com/profile/personal_access_tokens/new'; + break; + case GitPlatform.gitlab: + urlStr = 'https://gitlab.com/-/user_settings/personal_access_tokens'; + break; + case GitPlatform.generic: + urlStr = ''; + break; + } + + if (urlStr.isEmpty) return; + + Clipboard.setData(ClipboardData(text: urlStr)); + + final uri = Uri.tryParse(urlStr); + if (uri != null) { + try { + final launched = await launchUrl(uri, mode: LaunchMode.externalApplication); + if (!launched) { + await launchUrl(uri, mode: LaunchMode.platformDefault); + } + } catch (e) { + debugPrint('[GitAccount] 启动浏览器失败: $e'); + } + } + + if (context.mounted) { + DialogUtils.showToast(context, l10n.gitTokenCopiedOpeningBrowser, type: ToastType.info); + } + } + + Future _handleSave(AppLocalizations l10n) async { + final token = _tokenCtrl.text.trim(); + if (token.isEmpty) { + setState(() => _verifyError = l10n.gitEnterTokenPrompt); + return; + } + + setState(() { + _isVerifying = true; + _verifyError = null; + }); + + // 自动调用 API 校验 Token 并抓取真实身份信息 + final verifyRes = await GitAccountService.instance.verifyTokenAndFetchUserInfo( + _platform, + token, + customServerUrl: _platform == GitPlatform.generic ? _serverUrlCtrl.text.trim() : null, + ); + + if (!mounted) return; + + if (!verifyRes.success) { + setState(() { + _isVerifying = false; + _verifyError = verifyRes.error ?? l10n.gitTokenVerifyFailed; + }); + return; + } + + final finalUsername = verifyRes.username ?? _usernameCtrl.text.trim(); + final finalEmail = verifyRes.email?.isNotEmpty == true ? verifyRes.email! : _emailCtrl.text.trim(); + final finalServerUrl = _platform == GitPlatform.generic + ? (_serverUrlCtrl.text.trim().isNotEmpty ? _serverUrlCtrl.text.trim() : _platform.defaultServerUrl) + : _platform.defaultServerUrl; + + final updated = GitAccount( + id: widget.editingAccount?.id ?? DateTime.now().millisecondsSinceEpoch.toString(), + platform: _platform, + username: finalUsername, + displayName: verifyRes.displayName ?? finalUsername, + email: finalEmail, + authType: GitAuthType.token, + token: token, + serverUrl: finalServerUrl, + avatarUrl: verifyRes.avatarUrl ?? widget.editingAccount?.avatarUrl, + isDefault: widget.editingAccount?.isDefault ?? false, + createdAt: widget.editingAccount?.createdAt ?? DateTime.now(), + ); + + Navigator.pop(context, updated); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final l10n = AppLocalizations.of(context)!; + final isEditing = widget.editingAccount != null; + + return AlertDialog( + title: Text(isEditing ? l10n.gitEditAccount : l10n.gitAddAccount), + content: SingleChildScrollView( + child: SizedBox( + width: 360, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // 平台选择器 + Wrap( + spacing: 8, + runSpacing: 8, + children: GitPlatform.values.map((p) { + final isSelected = _platform == p; + final pName = p == GitPlatform.generic ? l10n.gitPlatformGeneric : p.name; + return ChoiceChip( + label: Text(pName), + selected: isSelected, + showCheckmark: false, + selectedColor: p.brandColor.withValues(alpha: 0.15), + labelStyle: TextStyle( + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, + color: isSelected ? p.brandColor : null, + ), + onSelected: (selected) { + if (selected) setState(() => _platform = p); + }, + ); + }).toList(), + ), + const SizedBox(height: 16), + + // 自建服务器 URL 输入 (多行输入,仅通用/自建 Git 需填写,GitHub、Gitee、GitLab 均为统一官方地址) + if (_platform == GitPlatform.generic) ...[ + TextField( + controller: _serverUrlCtrl, + minLines: 2, + maxLines: 4, + keyboardType: TextInputType.url, + decoration: InputDecoration( + labelText: l10n.gitServerUrl, + hintText: 'https://git.example.com', + prefixIcon: const Icon(Icons.link_rounded), + border: const OutlineInputBorder(), + isDense: true, + ), + ), + const SizedBox(height: 12), + ], + + // 令牌输入 (多行输入) + TextField( + controller: _tokenCtrl, + minLines: 2, + maxLines: 4, + keyboardType: TextInputType.multiline, + decoration: InputDecoration( + labelText: l10n.gitTokenLabel, + hintText: l10n.gitTokenHint, + prefixIcon: const Icon(Icons.vpn_key_outlined), + suffixIcon: IconButton( + icon: const Icon(Icons.content_paste_outlined, size: 20), + tooltip: l10n.paste, + onPressed: () async { + final data = await Clipboard.getData(Clipboard.kTextPlain); + if (data?.text != null && data!.text!.isNotEmpty) { + _tokenCtrl.text = data.text!.trim(); + } + }, + ), + border: const OutlineInputBorder(), + isDense: true, + ), + ), + + // 快捷前往获取 Token (自建 Git 无统一平台网页,不展示该按钮) + if (_platform != GitPlatform.generic) ...[ + const SizedBox(height: 6), + Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + style: TextButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + ), + icon: const Icon(Icons.open_in_new, size: 14), + label: Text( + l10n.gitGetToken, + style: const TextStyle(fontSize: 12), + ), + onPressed: () => _openTokenUrl(context, l10n), + ), + ), + ], + + if (_verifyError != null) ...[ + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: colorScheme.errorContainer.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + _verifyError!, + style: TextStyle(fontSize: 12, color: colorScheme.error), + ), + ), + ], + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: _isVerifying ? null : () => Navigator.pop(context), + child: Text(l10n.cancel), + ), + FilledButton( + onPressed: _isVerifying ? null : () => _handleSave(l10n), + child: _isVerifying + ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) + : Text(l10n.gitVerifyAndSave), + ), + ], + ); + } +} diff --git a/lib/views/main_view.dart b/lib/views/main_view.dart index 6c8848d..7ce79f6 100644 --- a/lib/views/main_view.dart +++ b/lib/views/main_view.dart @@ -144,18 +144,19 @@ class _MainViewState extends State { void _checkLspForFile(String filePath) async { final ext = p.extension(filePath); - if (ext.isEmpty) return; + final filename = p.basename(filePath); + if (ext.isEmpty && filename.isEmpty) return; await LspConfigService.instance.loadConfigs(); - // 1. 先检查已安装配置中是否有匹配此后缀的组件 - final existing = LspConfigService.instance.findByExtension(ext); + // 1. 先检查已安装配置中是否有匹配此后缀/文件名的组件 + final existing = LspConfigService.instance.findByExtension(ext, filename: filename); if (existing != null) return; final engineInstalled = await InternalEngineService.instance.isEngineInstalled(); if (!engineInstalled) return; // 2. 未在已安装配置中,查找代码内置语言预设模版 - final builtin = LspLanguageConfig.findBuiltinByExtension(ext); + final builtin = LspLanguageConfig.findBuiltinByExtension(ext, filename: filename); if (builtin == null) return; final isInstalled = await InternalEngineService.instance.isCommandInstalled(builtin.serverCommand); @@ -202,8 +203,8 @@ class _MainViewState extends State { if (install == true && mounted) { final success = await DialogUtils.showSyncLoadingDialog( context, - message: l10n.installingComponent(config.package), - task: () => InternalEngineService.instance.installPackage(config.package), + message: l10n.installingComponent(config.name), + task: () => InternalEngineService.instance.installLspConfig(config), ); if (mounted) { diff --git a/lib/widgets/git/git_panel_widget.dart b/lib/widgets/git/git_panel_widget.dart index e805c2d..0eedde8 100644 --- a/lib/widgets/git/git_panel_widget.dart +++ b/lib/widgets/git/git_panel_widget.dart @@ -11,6 +11,7 @@ import '../../utils/dialog_utils.dart'; import '../../utils/file_icon_utils.dart'; import 'git_diff_page.dart'; import 'git_graph_painter.dart'; +import '../../views/git_account_management_view.dart'; /// Git 版本控制侧边栏面板组件 class GitPanelWidget extends StatefulWidget { @@ -117,7 +118,7 @@ class _GitPanelWidgetState extends State { bottom: false, left: false, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 8.0), + padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, @@ -125,125 +126,164 @@ class _GitPanelWidgetState extends State { // 第一行:标题、多仓库切换、刷新、更多操作 Row( children: [ - // 标题 - Text( - l10n.drawerTabGit, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.bold, + // 标题与多仓库切换区(自适应宽度,杜绝水平溢出) + Expanded( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + l10n.drawerTabGit, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + if (repos.length > 1) ...[ + const SizedBox(width: 6), + PopupMenuButton( + tooltip: l10n.gitSwitchRepo, + initialValue: gitProvider.currentRepoPath, + onSelected: (path) => gitProvider.switchRepository(path), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3), + decoration: BoxDecoration( + color: theme.colorScheme.surface.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), + width: 0.8, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.source_outlined, + size: 13, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 3), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 80), + child: Text( + currentRepo?.name ?? l10n.gitRepository, + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + ), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + const SizedBox(width: 1), + Icon( + Icons.arrow_drop_down, + size: 14, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), + ), + itemBuilder: (ctx) { + return repos.map((r) { + final isSelected = r.rootPath == gitProvider.currentRepoPath; + return PopupMenuItem( + value: r.rootPath, + child: Row( + children: [ + Icon( + r.isRoot ? Icons.folder_special_outlined : Icons.folder_outlined, + size: 16, + color: isSelected ? theme.colorScheme.primary : null, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + r.name, + style: TextStyle( + fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, + fontSize: 13, + ), + overflow: TextOverflow.ellipsis, + ), + if (r.currentBranch != null) + Text( + r.currentBranch!, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + if (isSelected) + Icon(Icons.check, size: 16, color: theme.colorScheme.primary), + ], + ), + ); + }).toList(); + }, + ), + ], + ], ), ), - const SizedBox(width: 8), + const SizedBox(width: 4), - // 多仓库切换下拉菜单(若发现多个仓库) - if (repos.length > 1) ...[ - PopupMenuButton( - tooltip: l10n.gitSwitchRepo, - initialValue: gitProvider.currentRepoPath, - onSelected: (path) => gitProvider.switchRepository(path), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: theme.colorScheme.surface.withValues(alpha: 0.6), - borderRadius: BorderRadius.circular(6), - border: Border.all( - color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), - width: 0.8, - ), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - Icons.source_outlined, - size: 14, - color: theme.colorScheme.primary, - ), - const SizedBox(width: 4), - ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 110), - child: Text( - currentRepo?.name ?? l10n.gitRepository, - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: theme.colorScheme.onSurface, - ), - overflow: TextOverflow.ellipsis, - maxLines: 1, - ), - ), - const SizedBox(width: 2), - Icon( - Icons.arrow_drop_down, - size: 16, - color: theme.colorScheme.onSurfaceVariant, - ), - ], + // 顶部操作按钮组 + Row( + mainAxisSize: MainAxisSize.min, + children: [ + // Git 账号管理入口 + SizedBox( + width: 24, + height: 24, + child: IconButton( + icon: const Icon(Icons.manage_accounts_outlined, size: 18), + tooltip: l10n.gitAccountManagement, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute(builder: (_) => const GitAccountManagementView()), + ); + }, ), ), - itemBuilder: (ctx) { - return repos.map((r) { - final isSelected = r.rootPath == gitProvider.currentRepoPath; - return PopupMenuItem( - value: r.rootPath, - child: Row( - children: [ - Icon( - r.isRoot ? Icons.folder_special_outlined : Icons.folder_outlined, - size: 16, - color: isSelected ? theme.colorScheme.primary : null, - ), - const SizedBox(width: 8), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - r.name, - style: TextStyle( - fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, - fontSize: 13, - ), - overflow: TextOverflow.ellipsis, - ), - if (r.currentBranch != null) - Text( - r.currentBranch!, - style: TextStyle( - fontSize: 11, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], - ), - ), - if (isSelected) - Icon(Icons.check, size: 16, color: theme.colorScheme.primary), - ], - ), - ); - }).toList(); - }, - ), - const SizedBox(width: 6), - ], - const Spacer(), + // 刷新按钮 + if (gitProvider.hasProject && gitProvider.gitInstalled) ...[ + const SizedBox(width: 4), + SizedBox( + width: 24, + height: 24, + child: IconButton( + icon: const Icon(Icons.refresh, size: 18), + tooltip: l10n.gitRefresh, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: gitProvider.isLoading ? null : () => gitProvider.refresh(), + ), + ), + ], - // 刷新按钮 - if (gitProvider.hasProject && gitProvider.gitInstalled) - IconButton( - icon: const Icon(Icons.refresh, size: 18), - tooltip: l10n.gitRefresh, - visualDensity: VisualDensity.compact, - onPressed: gitProvider.isLoading ? null : () => gitProvider.refresh(), - ), - - // 更多操作 (撤销上次提交、Stash 贮藏等) - if (gitProvider.hasProject && gitProvider.gitInstalled && gitProvider.hasRepository) - _buildMoreActionsMenu(context, theme, l10n, gitProvider), + // 更多操作 (撤销上次提交、Stash 贮藏等) + if (gitProvider.hasProject && gitProvider.gitInstalled && gitProvider.hasRepository) ...[ + const SizedBox(width: 4), + _buildMoreActionsMenu(context, theme, l10n, gitProvider), + ], + ], + ), ], ), @@ -511,11 +551,14 @@ class _GitPanelWidgetState extends State { AppLocalizations l10n, GitProvider gitProvider, ) { - return PopupMenuButton( - icon: const Icon(Icons.more_vert, size: 18), - tooltip: l10n.gitMoreActions, - padding: EdgeInsets.zero, - onSelected: (action) async { + return SizedBox( + width: 24, + height: 24, + child: PopupMenuButton( + icon: const Icon(Icons.more_vert, size: 18), + tooltip: l10n.gitMoreActions, + padding: EdgeInsets.zero, + onSelected: (action) async { switch (action) { case 'undo_commit': _handleUndoLastCommit(context, l10n, gitProvider); @@ -566,7 +609,8 @@ class _GitPanelWidgetState extends State { ), ), ], - ); + ), + ); } /// 创建新分支对话框 diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index e71a16d..f6f23bf 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,6 +6,10 @@ #include "generated_plugin_registrant.h" +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 9e99d62..aec746f 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 438e7e5..ef89af8 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -7,8 +7,10 @@ import Foundation import file_picker import shared_preferences_foundation +import url_launcher_macos func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) } diff --git a/pubspec.lock b/pubspec.lock index d109d7a..e2a96cc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -609,6 +609,70 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" + url: "https://pub.dev" + source: hosted + version: "6.3.33" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" + url: "https://pub.dev" + source: hosted + version: "6.4.2" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" + url: "https://pub.dev" + source: hosted + version: "3.2.6" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" + url: "https://pub.dev" + source: hosted + version: "3.1.6" vector_math: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 5b6cfa8..53c91d1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -32,6 +32,7 @@ dependencies: xterm: path: packages/xterm flutter_pty: ^0.4.1 + url_launcher: ^6.3.2 dev_dependencies: flutter_test: diff --git a/test/container_runtime_chroot_test.dart b/test/container_runtime_chroot_test.dart index 91a2a1c..88aa625 100644 --- a/test/container_runtime_chroot_test.dart +++ b/test/container_runtime_chroot_test.dart @@ -14,17 +14,29 @@ import 'package:code_editor/views/settings_view.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); + late Directory tempBaseDir; + setUp(() { SharedPreferences.setMockInitialValues({}); RootService.instance.mockRootCapable = null; RootService.instance.mockRootGranted = null; ChrootMountManager.instance.mockPrepareSuccess = null; + + tempBaseDir = Directory.systemTemp.createTempSync('distro_test_'); + DistroManager().customBaseDir = tempBaseDir; + final ubuntuRootfs = Directory('${tempBaseDir.path}/ubuntu/rootfs')..createSync(recursive: true); + Directory('${ubuntuRootfs.path}/etc').createSync(recursive: true); + Directory('${ubuntuRootfs.path}/bin').createSync(recursive: true); }); tearDown(() { RootService.instance.mockRootCapable = null; RootService.instance.mockRootGranted = null; ChrootMountManager.instance.mockPrepareSuccess = null; + DistroManager().customBaseDir = null; + try { + tempBaseDir.deleteSync(recursive: true); + } catch (_) {} }); group('RootService Tests', () { @@ -242,6 +254,7 @@ void main() { context: testContext, settings: settings, showToast: true, + customRootDir: mockRootDir, ); expect(result, equals(ContainerRuntimeType.proot)); @@ -280,6 +293,7 @@ void main() { context: testContext, settings: settings, showToast: true, + customRootDir: mockRootDir, ); expect(result, equals(ContainerRuntimeType.chroot)); @@ -318,6 +332,7 @@ void main() { context: testContext, settings: settings, showToast: true, + customRootDir: mockRootDir, ); // Should smoothly fall back to proot diff --git a/test/git_account_test.dart b/test/git_account_test.dart new file mode 100644 index 0000000..bf8f1d2 --- /dev/null +++ b/test/git_account_test.dart @@ -0,0 +1,275 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:code_editor/l10n/app_localizations.dart'; +import 'package:code_editor/models/git_account.dart'; +import 'package:code_editor/services/distro_manager.dart'; +import 'package:code_editor/services/git_account_service.dart'; +import 'package:code_editor/services/internal_engine_service.dart'; +import 'package:code_editor/views/git_account_management_view.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('GitAccount Model Tests', () { + test('Serializes to and from JSON correctly', () { + final now = DateTime.now(); + final account = GitAccount( + id: 'acc_1', + platform: GitPlatform.github, + username: 'alice', + displayName: 'Alice Developer', + email: 'alice@example.com', + authType: GitAuthType.token, + token: 'ghp_secret12345', + serverUrl: 'https://github.com', + avatarUrl: 'https://avatars.githubusercontent.com/u/12345', + isDefault: true, + createdAt: now, + ); + + final json = account.toJson(); + expect(json['id'], 'acc_1'); + expect(json['platform'], 'github'); + expect(json['username'], 'alice'); + expect(json['token'], 'ghp_secret12345'); + expect(json['isDefault'], true); + + final parsed = GitAccount.fromJson(json); + expect(parsed.id, account.id); + expect(parsed.platform, GitPlatform.github); + expect(parsed.username, 'alice'); + expect(parsed.displayName, 'Alice Developer'); + expect(parsed.email, 'alice@example.com'); + expect(parsed.token, 'ghp_secret12345'); + expect(parsed.isDefault, true); + }); + + test('GitPlatform parsing handles fallback', () { + expect(GitPlatform.fromString('github'), GitPlatform.github); + expect(GitPlatform.fromString('gitee'), GitPlatform.gitee); + expect(GitPlatform.fromString('gitlab'), GitPlatform.gitlab); + expect(GitPlatform.fromString('unknown'), GitPlatform.github); + }); + }); + + group('GitAccountService Tests', () { + late Directory tempDir; + late GitAccountService service; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('git_account_test_'); + service = GitAccountService.instance; + service.customBaseDir = tempDir; + }); + + tearDown(() { + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + test('Initial load returns empty list', () async { + final accounts = await service.loadAccounts(forceReload: true); + expect(accounts, isEmpty); + }); + + test('Saves, sets default, and deletes accounts correctly', () async { + final acc1 = GitAccount( + id: 'acc_1', + platform: GitPlatform.github, + username: 'alice', + serverUrl: 'https://github.com', + token: 'token1', + createdAt: DateTime.now(), + ); + + final acc2 = GitAccount( + id: 'acc_2', + platform: GitPlatform.github, + username: 'bob', + serverUrl: 'https://github.com', + token: 'token2', + createdAt: DateTime.now(), + ); + + final acc3 = GitAccount( + id: 'acc_3', + platform: GitPlatform.gitee, + username: 'charlie', + serverUrl: 'https://gitee.com', + token: 'token3', + createdAt: DateTime.now(), + ); + + await service.saveAccount(acc1); + await service.saveAccount(acc2); + await service.saveAccount(acc3); + + expect(service.accounts.length, 3); + // acc1 was the first GitHub account, so it became default + final loaded1 = service.accounts.firstWhere((a) => a.id == 'acc_1'); + expect(loaded1.isDefault, true); + + // Change default GitHub account to acc2 + await service.setDefaultAccount('acc_2'); + final updated1 = service.accounts.firstWhere((a) => a.id == 'acc_1'); + final updated2 = service.accounts.firstWhere((a) => a.id == 'acc_2'); + expect(updated1.isDefault, false); + expect(updated2.isDefault, true); + + // Gitee account default is independent + final updated3 = service.accounts.firstWhere((a) => a.id == 'acc_3'); + expect(updated3.isDefault, true); + + // Match account by URL + final matchedGitHub = service.findAccountForUrl('https://github.com/org/repo.git'); + expect(matchedGitHub?.id, 'acc_2'); + + final matchedGitee = service.findAccountForUrl('https://gitee.com/user/project.git'); + expect(matchedGitee?.id, 'acc_3'); + + // Delete account + await service.deleteAccount('acc_1'); + expect(service.accounts.length, 2); + expect(service.accounts.any((a) => a.id == 'acc_1'), false); + }); + + test('SSH key persistence survives container reset', () async { + // 1. Simulate container with rootfs + final rootfsDir = Directory('${tempDir.path}/rootfs'); + final containerSshDir = Directory('${rootfsDir.path}/root/.ssh'); + containerSshDir.createSync(recursive: true); + final pubFile = File('${containerSshDir.path}/id_ed25519.pub'); + final privFile = File('${containerSshDir.path}/id_ed25519'); + pubFile.writeAsStringSync('ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGo4 test@key'); + privFile.writeAsStringSync('dummy_private_key_content'); + + File('${rootfsDir.path}/.installed').createSync(); + InternalEngineService.instance.customEngineDir = rootfsDir; + + // 2. Reading public key should back it up to host persistent directory + final key = await service.getSshPublicKey(); + expect(key, 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGo4 test@key'); + + final hostSshDir = await service.getPersistentSshDir(); + final hostPubFile = File('${hostSshDir.path}/id_ed25519.pub'); + expect(hostPubFile.existsSync(), isTrue); + expect(hostPubFile.readAsStringSync().trim(), 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGo4 test@key'); + + // 3. Simulate container rebuild / wipe (/root/.ssh is completely deleted) + containerSshDir.deleteSync(recursive: true); + expect(pubFile.existsSync(), isFalse); + + // 4. Calling getSshPublicKey again should restore key from persistent storage + final restoredKey = await service.getSshPublicKey(); + expect(restoredKey, 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGo4 test@key'); + expect(pubFile.existsSync(), isTrue); + }); + }); + + group('GitAccountManagementView Localization and UI Tests', () { + late Directory tempDir; + + setUp(() async { + tempDir = Directory.systemTemp.createTempSync('git_acc_ui_test_'); + GitAccountService.instance.customBaseDir = tempDir; + InternalEngineService.instance.customEngineDir = tempDir; + DistroManager().customBaseDir = tempDir; + await GitAccountService.instance.loadAccounts(forceReload: true); + }); + + tearDown(() { + GitAccountService.instance.customBaseDir = null; + InternalEngineService.instance.customEngineDir = null; + DistroManager().customBaseDir = null; + try { + tempDir.deleteSync(recursive: true); + } catch (_) {} + }); + + testWidgets('Renders in English correctly with no overflow', (tester) async { + await tester.binding.setSurfaceSize(const Size(320, 640)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + await tester.pumpWidget( + const MaterialApp( + locale: Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: GitAccountManagementView(), + ), + ); + + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpAndSettle(); + + expect(find.text('Git Accounts'), findsOneWidget); + expect(find.text('Hosted Accounts'), findsOneWidget); + expect(find.text('SSH Keys'), findsOneWidget); + expect(find.text('No Git Accounts Connected'), findsOneWidget); + }); + + testWidgets('Renders in Chinese correctly with no overflow', (tester) async { + await tester.binding.setSurfaceSize(const Size(320, 640)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + await tester.pumpWidget( + const MaterialApp( + locale: Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: GitAccountManagementView(), + ), + ); + + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpAndSettle(); + + expect(find.text('Git 账号管理'), findsOneWidget); + expect(find.text('托管账号'), findsOneWidget); + expect(find.text('SSH 密钥'), findsOneWidget); + expect(find.text('暂未绑定 Git 账号'), findsOneWidget); + }); + + testWidgets('Renders Account Card in English correctly with no overflow on narrow screen', (tester) async { + await tester.binding.setSurfaceSize(const Size(320, 640)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + final testAccount = GitAccount( + id: 'acc_narrow', + platform: GitPlatform.github, + username: 'superlongusernameexample', + displayName: 'Super Long User Name Example', + email: 'superlongdeveloperemail@example.com', + authType: GitAuthType.token, + token: 'token123', + serverUrl: 'https://github.com', + isDefault: true, + createdAt: DateTime.now(), + ); + await tester.runAsync(() async { + await GitAccountService.instance.saveAccount(testAccount); + }); + + await tester.pumpWidget( + const MaterialApp( + locale: Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: GitAccountManagementView(), + ), + ); + + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpAndSettle(); + + expect(find.text('Super Long User Name Example'), findsOneWidget); + expect(find.text('Default'), findsOneWidget); + expect(find.text('Personal Access Token'), findsOneWidget); + }); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart index 7161ae1..1eea739 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -45,6 +45,8 @@ import 'package:code_editor/widgets/code_editor_drawer.dart'; import 'package:code_editor/utils/dialog_utils.dart'; import 'package:code_editor/services/file_watcher_service.dart'; import 'package:code_editor/utils/syntax_highlight_helper.dart'; +import 'package:code_editor/providers/git_provider.dart'; +import 'package:code_editor/widgets/git/git_panel_widget.dart'; import 'package:shared_preferences/shared_preferences.dart'; /// 记录调用参数的测试用 sink,用于断言键盘组件把什么语义交给了下方实现 @@ -3415,6 +3417,23 @@ void main() { ); await scrollAll(tester); }); + + testWidgets('GitPanelWidget header on narrow drawer in English (no overflow)', (tester) async { + final gitProvider = GitProvider(); + await pumpNarrow( + tester, + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: gitProvider), + ], + child: localizedApp( + const Scaffold(body: GitPanelWidget()), + locale: const Locale('en'), + ), + ), + ); + expect(find.text('Source Control'), findsOneWidget); + }); }); // ============================================================ diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 48de52b..a0d0bbe 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -7,8 +7,11 @@ #include "generated_plugin_registrant.h" #include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { PermissionHandlerWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); } diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index b778eff..b257a14 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -4,6 +4,7 @@ list(APPEND FLUTTER_PLUGIN_LIST permission_handler_windows + url_launcher_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST