import 'package:cutdex/l10n/l10n.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../integrations/platform/file_picker.dart'; import '../../shared/widgets/workspace_card.dart'; import '../../shared/layout/workspace_layout_metrics.dart'; import '../../workspace/persistence/project_location_directory.dart'; import 'package:cutdex_ui/icons.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import 'appearance_settings.dart'; import 'timeline_ruler_settings_field.dart'; import 'language_settings.dart'; import 'location_settings.dart'; import 'mcp_settings_panel.dart'; import 'settings_layout.dart'; import '../../settings/settings_operation.dart'; import 'update_settings.dart'; import 'diagnostic_settings.dart'; import 'agent_settings_panel.dart'; const _settingsContentPadding = EdgeInsets.fromLTRB(20, 48, 20, 20); class SettingsContent extends ConsumerStatefulWidget { const SettingsContent({ super.key, this.workspace, this.initialTab = 0, this.navigationRequest = 0, this.cardLayout = false, this.onBack, }) : assert(initialTab >= 0 && initialTab <= 3); final int initialTab; final int navigationRequest; final bool cardLayout; final VoidCallback? onBack; final (String, String)? workspace; @override ConsumerState createState() => _SettingsContentState(); } class _SettingsContentState extends ConsumerState { late int _tab = widget.initialTab; Widget _surface(String name, Widget child) => widget.cardLayout ? WorkspaceCard(key: Key('settings-$name-card'), child: child) : child; @override void didUpdateWidget(covariant SettingsContent oldWidget) { super.didUpdateWidget(oldWidget); if (widget.initialTab != oldWidget.initialTab || widget.navigationRequest != oldWidget.navigationRequest) { _tab = widget.initialTab; } } Future _setMode(AppAppearance appearance) async { await ref .read(settingsOperationProvider('appearance').notifier) .run( () => ref.read(appearanceSettingsProvider.notifier).setMode(appearance), ); } Future _setPalette(AppPalette palette) async { await ref .read(settingsOperationProvider('palette').notifier) .run( () => ref.read(paletteSettingsProvider.notifier).setPalette(palette), ); } Future _setLanguage(AppLanguage language) async { await ref .read(settingsOperationProvider('language').notifier) .run( () => ref.read(languageSettingsProvider.notifier).setLanguage(language), ); } @override Widget build(BuildContext context) => Theme( data: AppTheme.settingsContentTheme(Theme.of(context)), child: Builder(builder: _buildContent), ); Widget _buildContent(BuildContext context) { return LayoutBuilder( builder: (context, constraints) => Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( width: constraints.maxWidth < 600 ? 96 : widget.cardLayout ? WorkspaceLayoutMetrics.sidebarDefaultWidth : 220, child: _surface( 'navigation', _SettingsNavigation( value: _tab, compact: constraints.maxWidth < 600, onBack: widget.onBack, onChanged: (value) => setState(() => _tab = value), ), ), ), if (widget.cardLayout) const SizedBox( key: Key('settings-card-gap'), width: WorkspaceLayoutMetrics.desktopSpacing, ) else const VerticalDivider( key: Key('settings-sidebar-divider'), width: 1, ), Expanded( child: _surface( 'content', ColoredBox( color: Theme.of(context).colorScheme.surface, child: IndexedStack( index: _tab, children: [ ExcludeFocus( excluding: _tab != 0, child: TickerMode( enabled: _tab == 0, child: SingleChildScrollView( primary: false, padding: _settingsContentPadding, child: SettingsPageSection( title: context.l10n.general, icon: AppIcons.settings, children: [ Consumer( builder: (context, ref, _) { final language = ref.watch( languageSettingsProvider, ); final languageSave = ref.watch( settingsOperationProvider('language'), ); return AppField( label: context.l10n.language, orientation: AppFieldOrientation.horizontal, error: (languageSave.hasError ? context.l10n.saveLanguageFailed : null) ?? (language.hasError ? context.l10n.loadLanguageFailed : null), child: SizedBox( width: AppSettingsMetrics.controlWidth, child: AppSelect( emptyLabel: context.l10n.noMatchingOptions, controlHeight: AppTheme.isDesktop(context) ? AppDesktopMetrics.button : AppSettingsMetrics.controlHeight, value: language.asData?.value ?? AppLanguage.system, label: context.l10n.language, options: [ for (final option in AppLanguage.values) AppSelectOption( option, option == AppLanguage.system ? context.l10n.system : option.nativeName, ), ], onChanged: languageSave.isLoading || language.isLoading ? null : _setLanguage, ), ), ); }, ), const _ProjectLocationField(), const _ResourceLocationField(), const UpdateSettings(), const DiagnosticSettings(), ], ), ), ), ), ExcludeFocus( excluding: _tab != 1, child: TickerMode( enabled: _tab == 1, child: const AgentSettingsPanel( contentPadding: _settingsContentPadding, ), ), ), ExcludeFocus( excluding: _tab != 2, child: TickerMode( enabled: _tab == 2, child: SingleChildScrollView( primary: false, padding: _settingsContentPadding, child: McpSettingsPanel(workspace: widget.workspace), ), ), ), ExcludeFocus( excluding: _tab != 3, child: TickerMode( enabled: _tab == 3, child: SingleChildScrollView( primary: false, padding: _settingsContentPadding, child: SettingsPageSection( title: context.l10n.appearance, icon: AppIcons.appearance, children: [ Consumer( builder: (context, ref, _) { final palette = ref.watch( paletteSettingsProvider, ); final paletteSave = ref.watch( settingsOperationProvider('palette'), ); return AppField( label: context.l10n.colorPalette, orientation: AppFieldOrientation.horizontal, error: (paletteSave.hasError ? context.l10n.saveAppearanceFailed : null) ?? (palette.hasError ? context.l10n.loadAppearanceFailed : null), child: SizedBox( width: AppSettingsMetrics.controlWidth, child: AppSelect( key: const Key( 'settings-color-palette', ), emptyLabel: context.l10n.noMatchingOptions, controlHeight: AppTheme.isDesktop(context) ? AppDesktopMetrics.button : AppSettingsMetrics.controlHeight, value: palette.asData?.value ?? AppPalette.graphite, label: context.l10n.colorPalette, options: [ AppSelectOption( AppPalette.graphite, context.l10n.paletteGraphite, ), AppSelectOption( AppPalette.violet, context.l10n.paletteViolet, ), AppSelectOption( AppPalette.teal, context.l10n.paletteTeal, ), ], onChanged: paletteSave.isLoading || palette.isLoading ? null : _setPalette, ), ), ); }, ), Consumer( builder: (context, ref, _) { final appearance = ref.watch( appearanceSettingsProvider, ); final appearanceSave = ref.watch( settingsOperationProvider('appearance'), ); return AppField( label: context.l10n.theme, orientation: AppFieldOrientation.horizontal, error: (appearanceSave.hasError ? context.l10n.saveAppearanceFailed : null) ?? (appearance.hasError ? context.l10n.loadAppearanceFailed : null), child: SizedBox( width: AppSettingsMetrics.controlWidth, child: AppSelect( emptyLabel: context.l10n.noMatchingOptions, controlHeight: AppTheme.isDesktop(context) ? AppDesktopMetrics.button : AppSettingsMetrics.controlHeight, value: appearance.asData?.value ?? AppAppearance.system, label: context.l10n.theme, options: [ AppSelectOption( AppAppearance.system, context.l10n.system, ), AppSelectOption( AppAppearance.penLight, context.l10n.light, ), AppSelectOption( AppAppearance.penDark, context.l10n.dark, ), ], onChanged: appearanceSave.isLoading || appearance.isLoading ? null : _setMode, ), ), ); }, ), const TimelineRulerSettingsField(), ], ), ), ), ), ], ), ), ), ), ], ), ); } } class _SettingsNavigation extends StatelessWidget { const _SettingsNavigation({ required this.value, required this.compact, required this.onChanged, this.onBack, }); final int value; final bool compact; final ValueChanged onChanged; final VoidCallback? onBack; @override Widget build(BuildContext context) { final theme = Theme.of(context); final entries = [ (0, context.l10n.general, AppIcons.settings), (3, context.l10n.appearance, AppIcons.appearance), (1, context.l10n.agentSettings, AppIcons.assistant), (2, 'MCP', AppIcons.terminal), ]; final title = Text( context.l10n.settings, style: theme.textTheme.titleSmall?.copyWith(fontSize: 16), maxLines: 1, overflow: TextOverflow.ellipsis, ); final back = IconButton( key: const Key('settings-sidebar-back'), tooltip: MaterialLocalizations.of(context).backButtonTooltip, onPressed: onBack, style: AppTheme.projectTabActionStyle(context, size: 28), icon: const Icon(AppIcons.arrowBack, size: 16), ); return ColoredBox( key: const Key('settings-sidebar'), color: AppTheme.settingsSidebarBackground(context), child: ListView( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), children: [ Padding( padding: const EdgeInsets.fromLTRB(8, 0, 8, 20), child: onBack == null ? title : compact ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [back, const SizedBox(height: 8), title], ) : Row( children: [ back, const SizedBox(width: 8), Expanded(child: title), ], ), ), for (var index = 0; index < entries.length; index++) Padding( padding: const EdgeInsets.only(bottom: 1), child: Semantics( selected: value == entries[index].$1, child: Tooltip( message: entries[index].$2, child: TextButton( key: ValueKey('settings-navigation-${entries[index].$1}'), onPressed: () => onChanged(entries[index].$1), style: TextButton.styleFrom( minimumSize: const Size(0, 30), padding: const EdgeInsets.symmetric(horizontal: 8), foregroundColor: theme.colorScheme.onSurface, backgroundColor: value == entries[index].$1 ? theme.colorScheme.onSurface.withValues(alpha: .078) : Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), alignment: AlignmentDirectional.centerStart, ), child: Row( children: [ if (!compact) ...[ Icon(entries[index].$3, size: 16), const SizedBox(width: 8), ], Expanded( child: Text( entries[index].$2, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ), ), ), ), ], ), ); } } class _ResourceLocationField extends ConsumerWidget { const _ResourceLocationField(); Future _choose( BuildContext context, WidgetRef ref, String? initialDirectory, ) async { final directory = await ref .read(filePickerProvider) .pickDirectory( initialDirectory: initialDirectory, confirmButtonText: context.l10n.select, ); if (directory == null || !context.mounted) return; await ref.read(resourceLocationSettingsProvider.notifier).save(directory); } @override Widget build(BuildContext context, WidgetRef ref) { final settings = ref.watch(resourceLocationSettingsProvider); final error = switch (settings.error) { LocationSettingsError.load => context.l10n.loadResourceLocationFailed, LocationSettingsError.save => context.l10n.saveResourceLocationFailed, null => null, }; return AppField( label: context.l10n.resourceLocation, orientation: AppFieldOrientation.horizontal, error: error, child: SizedBox( width: 420, child: Row( children: [ Expanded( child: Tooltip( message: settings.directory ?? context.l10n.resourceLocationNotSet, child: _MiddleEllipsisText( settings.directory ?? context.l10n.resourceLocationNotSet, key: const Key('resource-location-value'), textAlign: TextAlign.right, ), ), ), const SizedBox(width: AppSpacing.compact), OutlinedButton( key: const Key('choose-resource-location'), onPressed: settings.loading || settings.saving ? null : () => _choose(context, ref, settings.directory), child: Text(context.l10n.modify), ), ], ), ), ); } } class _ProjectLocationField extends ConsumerWidget { const _ProjectLocationField(); Future _choose( BuildContext context, WidgetRef ref, String? initialDirectory, ) async { final directory = await ref .read(filePickerProvider) .pickDirectory( initialDirectory: initialDirectory, confirmButtonText: context.l10n.select, ); if (directory == null || !context.mounted) return; await ref.read(projectLocationSettingsProvider.notifier).save(directory); } @override Widget build(BuildContext context, WidgetRef ref) { final settings = ref.watch(projectLocationSettingsProvider); final error = switch (settings.error) { LocationSettingsError.load => context.l10n.loadProjectLocationFailed, LocationSettingsError.save => context.l10n.saveProjectLocationFailed, null => null, }; return AppField( label: context.l10n.projectLocation, orientation: AppFieldOrientation.horizontal, description: settings.status == ProjectLocationStatus.missing ? context.l10n.projectLocationMissing : null, error: error ?? switch (settings.status) { ProjectLocationStatus.unavailable => context.l10n.projectLocationUnavailable, ProjectLocationStatus.notWritable => context.l10n.projectLocationNotWritable, _ => null, }, child: SizedBox( width: 420, child: Row( children: [ Expanded( child: Tooltip( message: settings.directory ?? context.l10n.projectLocationNotSet, child: _MiddleEllipsisText( settings.directory ?? context.l10n.projectLocationNotSet, key: const Key('project-location-value'), textAlign: TextAlign.right, ), ), ), const SizedBox(width: AppSpacing.compact), if (error != null || settings.status == ProjectLocationStatus.unavailable || settings.status == ProjectLocationStatus.notWritable) TextButton( key: const Key('retry-project-location'), onPressed: settings.loading || settings.saving ? null : ref.read(projectLocationSettingsProvider.notifier).reload, child: Text(context.l10n.retry), ), OutlinedButton( key: const Key('choose-project-location'), onPressed: settings.loading || settings.saving ? null : () => _choose(context, ref, settings.directory), child: Text(context.l10n.modify), ), ], ), ), ); } } class _MiddleEllipsisText extends StatelessWidget { const _MiddleEllipsisText( this.text, { super.key, this.textAlign = TextAlign.start, }); final String text; final TextAlign textAlign; @override Widget build(BuildContext context) { final style = DefaultTextStyle.of(context).style; final direction = Directionality.of(context); return LayoutBuilder( builder: (context, constraints) => Text( _ellipsize(text, constraints.maxWidth, style, direction), maxLines: 1, textAlign: textAlign, ), ); } static String _ellipsize( String value, double maxWidth, TextStyle style, TextDirection direction, ) { bool fits(String candidate) { final painter = TextPainter( text: TextSpan(text: candidate, style: style), maxLines: 1, textDirection: direction, )..layout(maxWidth: maxWidth); return !painter.didExceedMaxLines && painter.width <= maxWidth; } if (!maxWidth.isFinite || fits(value)) return value; var low = 0; var high = value.length; while (low < high) { final keep = (low + high + 1) ~/ 2; final leading = (keep + 1) ~/ 2; final candidate = '${value.substring(0, leading)}…' '${value.substring(value.length - (keep - leading))}'; if (fits(candidate)) { low = keep; } else { high = keep - 1; } } final leading = (low + 1) ~/ 2; return '${value.substring(0, leading)}…' '${value.substring(value.length - (low - leading))}'; } }