refactor(desktop): reorganize workspace panels and navigation
Gitea CI / Windows x64 and Android (pull_request) Successful in 16m21s
Gitea CI / Gitea CI passed (pull_request) Successful in 3s

This commit is contained in:
lingjhf committed 2026-10-06 12:11:59 +08:00
1 parent 826745b407
commit 1f73765745
92 files changed
+5811 -2650

No files matched your search

+11 -7
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart';
@@ -18,7 +20,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../settings/settings_dialog.dart';
import '../settings/settings_page.dart';
import 'chat_controller.dart';
import 'chat_state.dart';
import '../../integrations/agent/conversation_repository.dart';
@@ -360,8 +362,10 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
if (saved) {
setState(() => _usingDraftModel = true);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)),
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.agentSaveSettingsFailed),
),
);
}
}
@@ -374,7 +378,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
return TextButton.icon(
key: const Key('agent-configure-model'),
style: compactButtonStyle,
onPressed: () => showSettingsDialog(context, initialTab: 1),
onPressed: () => showSettingsPage(context, initialTab: 1),
icon: const Icon(Icons.tune, size: 16),
label: Text(context.l10n.agentConfigureModel),
);
@@ -398,11 +402,11 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
AppMenuItem(
label: context.l10n.agentConfigureModel,
selectOption: true,
onPressed: () => showSettingsDialog(context, initialTab: 1),
onPressed: () => showSettingsPage(context, initialTab: 1),
),
],
builder: (context, toggle, focus) => TextButton(
key: const Key('agent-model-picker'),
builder: (context, toggle, focus) => AppToolbarDropdownButton(
buttonKey: const Key('agent-model-picker'),
focusNode: focus,
onPressed: () {
if (!state.busy && !_choosingModel) toggle?.call();
@@ -97,6 +97,18 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
final projects = widget.projects
.where((project) => project.name.toLowerCase().contains(query))
.toList();
final listHeight = projects.isEmpty
? ComposerLayout.menuRowHeight +
AppComposerStyle.menuEmptyPadding.vertical
: (projects.length * ComposerLayout.menuRowHeight).clamp(
0.0,
ComposerLayout.menuListMaxHeight,
);
final contentHeight =
ComposerLayout.menuRowHeight * 2 +
(AppComposerStyle.menuSeparatorPadding.vertical + 1) * 2 +
listHeight;
final menuHeight = contentHeight + ComposerLayout.menuGutter * 2;
return Material(
key: const Key('composer-project-bar'),
color: widget.backgroundColor,
@@ -109,12 +121,15 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
alignment: AlignmentDirectional.centerStart,
child: MenuAnchor(
controller: _menu,
alignmentOffset: Offset(0, -menuHeight - 4),
consumeOutsideTap: false,
onClose: () => setState(_search.clear),
style: AppComposerStyle.projectMenu(context),
style: AppComposerStyle.projectMenu(context)
.copyWith(alignment: AlignmentDirectional.topStart),
menuChildren: [
SizedBox(
width: ComposerLayout.menuContentWidth,
height: contentHeight,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -134,10 +149,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
),
),
_separator(),
ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: ComposerLayout.menuListMaxHeight,
),
Expanded(
child: SingleChildScrollView(
primary: false,
child: Column(
@@ -14,7 +14,9 @@ import 'package:cutdex_ui/widgets.dart';
import '../media/background_tasks_dialog.dart';
class BackgroundTasksButton extends ConsumerWidget {
const BackgroundTasksButton({super.key});
const BackgroundTasksButton({super.key, this.iconSize = AppIconSize.header});
final double iconSize;
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -40,7 +42,7 @@ class BackgroundTasksButton extends ConsumerWidget {
onPressed: toggle,
icon: Badge(
isLabelVisible: hasRunningTasks(),
child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header),
child: Icon(Icons.task_alt_outlined, size: iconSize),
),
);
return AppPopover(
+179 -165
View File
@@ -22,6 +22,7 @@ import '../properties/properties_editor_page.dart';
import '../properties/properties_panel.dart';
import '../timeline/timeline_panel.dart';
import 'editor_presentation_controller.dart';
import 'editor_panel_defaults.dart';
import 'layouts/bounded_editor_layout.dart';
import 'layouts/expanded_editor_layout.dart';
@@ -34,10 +35,12 @@ class EditorWorkspace extends ConsumerStatefulWidget {
required this.projectName,
required this.integratedTitlebar,
required this.headerLeading,
this.projectLoading = false,
this.showProjectName = true,
this.experience = DeviceExperience.desktop,
});
final bool projectLoading;
final String projectId;
final String timelineId;
final String projectName;
@@ -79,53 +82,170 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
child: EditorPreviewPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: widget.projectLoading,
),
);
final timeline = EditorTimelinePanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: widget.projectLoading,
);
final properties = EditorPropertiesPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
);
final media = MediaPanel(projectId: widget.projectId);
final properties = widget.projectLoading
? const EditorEmptyPanel()
: EditorPropertiesPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
);
final media = widget.projectLoading
? const EditorEmptyPanel()
: MediaPanel(projectId: widget.projectId);
return ListenableBuilder(
listenable: ref.watch(editorPresentationProvider(widget.projectId)),
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final desktop = widget.experience == DeviceExperience.desktop;
final sideWidth =
(_presentation.mediaOpen
? WorkspaceLayoutMetrics.mediaPanelWidth + 1
: 0) +
(_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
: 0);
final sideWidth = (_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
: 0);
final dockPanels =
desktop &&
constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
final desktopTool = sideWidth == 0
? null
: _presentation.desktopTool(propertiesOpen: _propertiesOpen);
final headerHeight = desktop ? AppControlSize.panelHeader : 48.0;
final mediaOpen = desktop
? dockPanels
? _presentation.mediaOpen
: desktopTool == EditorTool.media
: _presentation.activeTool == EditorTool.media;
final desktopTool = _propertiesOpen ? EditorTool.properties : null;
final headerHeight = desktop ? AppControlSize.panelToolbar : 48.0;
final mediaOpen = _presentation.activeTool == EditorTool.media;
final propertiesOpen = desktop
? dockPanels
? _propertiesOpen
: desktopTool == EditorTool.properties
: _presentation.activeTool == EditorTool.properties;
final header = Material(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
key: const Key('editor-content-header'),
height: headerHeight,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding(
child: Row(
children: [
widget.headerLeading,
Expanded(
child: widget.showProjectName
? Row(
children: [
Flexible(
fit: FlexFit.loose,
child: Text(
widget.projectName,
key: const Key('workspace-project-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.titleSmall,
),
),
Flexible(
fit: FlexFit.loose,
child: widget.projectLoading
? const SizedBox.shrink()
: _TimelineSaveStatus(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
],
)
: const SizedBox.shrink(),
),
if (!desktop)
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('editor-media-button'),
tooltip: context.l10n.materials,
isSelected: mediaOpen,
onPressed: () {
if (desktop) {
if (!dockPanels &&
desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(
EditorTool.media,
);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(EditorTool.media);
}
},
icon: const Icon(Icons.perm_media_outlined),
),
),
),
if (!desktop) const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop ? AppControlSize.headerButton : 48,
child: IconButton(
key: const Key('editor-properties-button'),
tooltip: propertiesOpen
? context.l10n.collapseProperties
: context.l10n.expandProperties,
isSelected: propertiesOpen,
onPressed: !viewSettings.hasValue
? null
: () {
if (desktop) {
if (dockPanels ||
desktopTool ==
EditorTool.properties ||
!_propertiesOpen) {
_viewController.setPropertiesOpen(
!_propertiesOpen,
);
_saveViewSettings();
}
_presentation.preferDesktopTool(
EditorTool.properties,
);
} else {
_presentation.toggleTool(
EditorTool.properties,
);
}
},
icon: const Icon(
Icons.tune,
size: AppIconSize.header,
),
),
),
),
if (!desktop) const SizedBox(width: AppSpacing.compact),
],
),
),
),
),
);
Widget dockedEditing({required bool showTools}) =>
ExpandedEditorLayout(
preview: preview,
header: header,
properties: properties,
media: media,
showMedia: showTools && _presentation.mediaOpen,
showMedia: false,
showProperties: showTools && _propertiesOpen,
timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) {
@@ -141,121 +261,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
children: [
Column(
children: [
Material(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
key: const Key('editor-content-header'),
height: headerHeight,
child: WindowHeaderPadding(
child: Row(
children: [
widget.headerLeading,
Expanded(
child: widget.showProjectName
? Row(
children: [
Flexible(
fit: FlexFit.loose,
child: Text(
widget.projectName,
key: const Key(
'workspace-project-title',
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.titleSmall,
),
),
Flexible(
fit: FlexFit.loose,
child: _TimelineSaveStatus(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
],
)
: const SizedBox.shrink(),
),
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('editor-media-button'),
tooltip: context.l10n.materials,
isSelected: mediaOpen,
onPressed: () {
if (desktop) {
if (!dockPanels &&
desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(
EditorTool.media,
);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(
EditorTool.media,
);
}
},
icon: const Icon(Icons.perm_media_outlined),
),
),
),
const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('editor-properties-button'),
tooltip: propertiesOpen
? context.l10n.collapseProperties
: context.l10n.expandProperties,
isSelected: propertiesOpen,
onPressed: !viewSettings.hasValue
? null
: () {
if (desktop) {
if (dockPanels ||
desktopTool ==
EditorTool.properties ||
!_propertiesOpen) {
_viewController.setPropertiesOpen(
!_propertiesOpen,
);
_saveViewSettings();
}
_presentation.preferDesktopTool(
EditorTool.properties,
);
} else {
_presentation.toggleTool(
EditorTool.properties,
);
}
},
icon: const Icon(
Icons.tune,
size: AppIconSize.header,
),
),
),
),
const SizedBox(width: AppSpacing.compact),
],
),
),
),
),
if (!desktop) header,
Expanded(
child: dockPanels
? dockedEditing(showTools: true)
@@ -270,26 +276,33 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
tool: desktop
? desktopTool
: _presentation.activeTool,
media: switch (widget.experience) {
DeviceExperience.desktop => media,
DeviceExperience.tablet => MediaBrowserDrawer(
projectId: widget.projectId,
),
DeviceExperience.phone => MediaBrowserPage(
projectId: widget.projectId,
),
},
properties: switch (widget.experience) {
DeviceExperience.desktop => properties,
DeviceExperience.tablet => PropertiesToolPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
DeviceExperience.phone => PropertiesEditorPage(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
},
media: widget.projectLoading
? media
: switch (widget.experience) {
DeviceExperience.desktop => media,
DeviceExperience.tablet =>
MediaBrowserDrawer(
projectId: widget.projectId,
),
DeviceExperience.phone => MediaBrowserPage(
projectId: widget.projectId,
),
},
properties: widget.projectLoading
? properties
: switch (widget.experience) {
DeviceExperience.desktop => properties,
DeviceExperience.tablet =>
PropertiesToolPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
DeviceExperience.phone =>
PropertiesEditorPage(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
},
onCloseTool: () {
if (!desktop) {
_presentation.closeTool();
@@ -304,14 +317,15 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
),
],
),
Positioned(
key: const Key('editing-top-divider'),
top: headerHeight,
left: 0,
right: 0,
height: 1,
child: const Divider(height: 1),
),
if (!desktop)
Positioned(
key: const Key('editing-top-divider'),
top: headerHeight,
left: 0,
right: 0,
height: 1,
child: const Divider(height: 1),
),
],
);
},
@@ -0,0 +1,62 @@
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
/// Empty values while a project's content is being bound to its cards.
class EditorEmptyPanel extends StatelessWidget {
const EditorEmptyPanel({super.key});
@override
Widget build(BuildContext context) =>
const WorkspacePanel(child: SizedBox.expand());
}
class EditorTimelineDefaults extends StatelessWidget {
const EditorTimelineDefaults({super.key, this.showTabs = true});
final bool showTabs;
@override
Widget build(BuildContext context) => Column(
children: [
if (showTabs) ...[
const SizedBox(
key: Key('timeline-tabs-bar'),
height: 26,
child: Row(
children: [
IconButton(onPressed: null, icon: Icon(Icons.add, size: 16)),
],
),
),
const Divider(height: 1),
],
Expanded(
child: WorkspacePanel(
headerHeight: 32,
headerPadding: EdgeInsets.zero,
controls: SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final icon in [
Icons.undo,
Icons.redo,
Icons.content_cut,
Icons.align_horizontal_left,
Icons.align_horizontal_right,
Icons.delete_outline,
])
IconButton(onPressed: null, icon: Icon(icon, size: 16)),
],
),
),
),
child: const SizedBox.expand(key: Key('timeline-default-tracks')),
),
),
],
);
}
@@ -36,7 +36,7 @@ class BoundedEditorLayout extends StatelessWidget {
Widget toolSurface() => Column(
children: [
SizedBox(
height: desktop ? AppControlSize.panelHeader : 48,
height: desktop ? AppControlSize.panelToolbar : 48,
child: Row(
children: [
SizedBox.square(
@@ -92,7 +92,7 @@ class BoundedEditorLayout extends StatelessWidget {
),
if (tool != null)
Positioned(
top: 0,
top: desktop ? AppControlSize.panelToolbar + 1 : 0,
bottom: 0,
right: 0,
width: page
@@ -1,14 +1,17 @@
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import '../../../shared/layout/workspace_layout_metrics.dart';
import '../../../shared/widgets/workspace_card.dart';
import '../../../shared/widgets/workspace_resize_handle.dart';
class ExpandedEditorLayout extends StatefulWidget {
const ExpandedEditorLayout({
super.key,
required this.preview,
required this.header,
required this.properties,
required this.media,
required this.showMedia,
@@ -20,6 +23,7 @@ class ExpandedEditorLayout extends StatefulWidget {
});
final Widget preview;
final Widget header;
final Widget properties;
final Widget media;
final bool showMedia;
@@ -34,15 +38,20 @@ class ExpandedEditorLayout extends StatefulWidget {
}
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
double? _timelineDragStartY;
double _timelineDragStartHeight = 0;
static const gap = WorkspaceLayoutMetrics.desktopSpacing;
Widget _card(String name, Widget child) =>
WorkspaceCard(key: Key('editor-$name-card'), child: child);
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
final maximum = math.max(
0.0,
constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight,
constraints.maxHeight -
gap -
AppControlSize.panelToolbar -
WorkspaceLayoutMetrics.timelineMinimumHeight,
);
final minimum = math.min(
WorkspaceLayoutMetrics.timelineMinimumHeight,
@@ -66,76 +75,72 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
Column(
children: [
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.showMedia) ...[
SizedBox(
key: const Key('editor-media-region'),
width: mediaWidth,
child: widget.media,
child: _card(
'preview',
Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
widget.header,
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.showMedia) ...[
SizedBox(
key: const Key('editor-media-region'),
width: mediaWidth,
child: widget.media,
),
const VerticalDivider(width: 1),
],
Expanded(child: widget.preview),
],
),
),
],
),
),
const VerticalDivider(width: 1),
if (widget.showProperties) ...[
const VerticalDivider(
key: Key('editor-properties-divider'),
width: 1,
),
SizedBox(
key: const Key('editor-properties-region'),
width: propertiesWidth,
child: widget.properties,
),
],
],
Expanded(child: widget.preview),
if (widget.showProperties) ...[
const VerticalDivider(width: 1),
SizedBox(
key: const Key('editor-properties-region'),
width: propertiesWidth,
child: widget.properties,
),
],
],
),
),
),
const SizedBox(height: 1),
SizedBox(height: timelineHeight, child: widget.timeline),
const SizedBox(height: gap),
SizedBox(
height: timelineHeight,
child: _card('timeline', widget.timeline),
),
],
),
Positioned(
key: const Key('editor-timeline-divider'),
left: 0,
right: 0,
bottom: timelineHeight - 4,
height: 8,
child: MouseRegion(
cursor: SystemMouseCursors.resizeRow,
child: GestureDetector(
key: const Key('editor-timeline-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onVerticalDragStart: (details) {
_timelineDragStartY = details.globalPosition.dy;
_timelineDragStartHeight = timelineHeight;
},
onVerticalDragUpdate: (details) {
final start = _timelineDragStartY;
if (start == null) return;
widget.onTimelineHeightChanged(
(_timelineDragStartHeight +
start -
details.globalPosition.dy)
.clamp(minimum, maximum)
.toDouble(),
);
},
onVerticalDragEnd: (_) {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
onVerticalDragCancel: () {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
child: const Center(
child: SizedBox(
height: 1,
width: double.infinity,
child: Divider(height: 1),
),
),
bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
child: WorkspaceResizeHandle(
key: const Key('editor-timeline-resize'),
axis: Axis.vertical,
initialValue: timelineHeight,
direction: -1,
onResize: (height) => widget.onTimelineHeightChanged(
height.clamp(minimum, maximum).toDouble(),
),
onEnd: widget.onTimelineHeightChangeEnd,
),
),
],
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'subtitle_download.dart';
@@ -691,8 +692,8 @@ class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> {
setState(() => _validationError = null);
await action();
if (mounted && !widget.details && _error != null) {
ScaffoldMessenger.maybeOf(context)
?.showSnackBar(SnackBar(content: Text(_error!)));
ErrorNotificationHost.maybeOf(context)
?.show(ErrorNotification(content: Text(_error!)));
}
}
+44 -25
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'dart:math' as math;
@@ -34,6 +35,7 @@ extension MediaFilterLabel on MediaFilter {
}
const maximumMediaGridTileWidth = 160.0;
const maximumCompactMediaGridTileWidth = 120.0;
class MediaBrowserBody extends ConsumerStatefulWidget {
const MediaBrowserBody({
@@ -41,10 +43,12 @@ class MediaBrowserBody extends ConsumerStatefulWidget {
required this.projectId,
required this.grid,
this.draggable = false,
this.compact = false,
});
final String projectId;
final bool grid;
final bool draggable;
final bool compact;
@override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
}
@@ -82,16 +86,11 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
Future<void> _action(Future<bool> Function() action) async {
final ok = await action();
if (!mounted || ok) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
context.l10n.failureMessage(
ref.read(projectsProvider).asData?.value.error ??
const AppFailure(AppErrorCode.operationFailed),
),
),
),
);
final failure =
ref.read(projectsProvider).asData?.value.error ??
const AppFailure(AppErrorCode.operationFailed);
ErrorNotificationHost.of(context)
.showFailure(failure, context.l10n.failureMessage(failure));
}
Future<void> _rename(AssetDocument asset) async {
@@ -166,7 +165,17 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
);
Widget _buildBrowser(BuildContext context) {
ref.watch(externalMediaImportProvider(widget.projectId));
final workspace = ref.watch(projectsProvider).asData?.value;
ref.watch(
projectsProvider.select(
(value) => (
value.value?.activeProject?.id,
value.value?.assets,
value.value?.timeline?.id,
value.value?.projectBusy,
),
),
);
final workspace = ref.read(projectsProvider).value;
final active = workspace?.activeProject?.id == widget.projectId;
final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _filter == MediaFilter.all
@@ -197,15 +206,22 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
)
: LayoutBuilder(
builder: (context, constraints) {
const spacing = AppSpacing.small;
final width = math.max(
1.0,
constraints.maxWidth - AppSpacing.compact * 2,
);
final spacing = widget.compact
? AppSpacing.gap
: AppSpacing.small;
final padding = widget.compact
? AppSidebarMetrics.outerPadding
: AppSpacing.compact;
final width = math.max(1.0, constraints.maxWidth - padding * 2);
final columns = math.max(
1,
((width + spacing) / (maximumMediaGridTileWidth + spacing))
.ceil(),
widget.compact
? ((width + spacing) /
(maximumCompactMediaGridTileWidth + spacing))
.ceil()
: ((width + spacing) /
(maximumMediaGridTileWidth + spacing))
.ceil(),
);
final tileWidth = (width - spacing * (columns - 1)) / columns;
final textStyle = Theme.of(context).textTheme.bodySmall!;
@@ -308,23 +324,26 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
? ListView.separated(
key: PageStorageKey(('media-list', widget.projectId)),
controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact),
padding: EdgeInsets.all(padding),
itemCount: assets.length,
itemBuilder: item,
separatorBuilder: (_, _) =>
const SizedBox(height: AppSpacing.small),
separatorBuilder: (_, _) => SizedBox(height: spacing),
)
: GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact),
padding: EdgeInsets.all(padding),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: spacing,
mainAxisSpacing: AppSpacing.compact,
mainAxisSpacing: widget.compact
? spacing
: AppSpacing.compact,
mainAxisExtent:
tileWidth * 9 / 16 +
AppSpacing.small +
(widget.compact
? AppSpacing.gap
: AppSpacing.small) +
labelHeight +
2,
),
@@ -403,7 +422,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
],
),
),
const SizedBox(height: AppSpacing.small),
SizedBox(height: widget.compact ? AppSpacing.gap : AppSpacing.small),
name,
],
);
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
@@ -74,7 +75,7 @@ class _MediaImportFeedbackListenerState
WidgetsBinding.instance.addPostFrameCallback((_) {
_scheduled = false;
if (!mounted || !_visible || !widget.feedback.hasPending) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final messenger = ErrorNotificationHost.maybeOf(context);
if (messenger == null) return;
for (final result in widget.feedback.takePending()) {
final messages = [
@@ -84,8 +85,13 @@ class _MediaImportFeedbackListenerState
'${failure.name}: ${context.l10n.failureMessage(failure.failure)}',
if (result?.failed == true) context.l10n.noImportableFiles,
];
messenger.showSnackBar(
SnackBar(
messenger.show(
ErrorNotification(
details: [
for (final failure
in result?.result?.failures ?? <MediaImportFailure>[])
'${failure.name}: code=${failure.failure.code.name}\n${failure.failure.diagnostic ?? ''}',
].join('\n'),
content: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(child: Text(messages.join('\n'))),
+3 -2
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -142,8 +143,8 @@ class TouchMediaBrowser extends ConsumerWidget {
selected,
);
if (!inserted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.operationFailed),
),
);
@@ -0,0 +1,241 @@
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
class MediaBrowserToolbar extends StatefulWidget {
const MediaBrowserToolbar({
super.key,
required this.canImport,
required this.onImport,
required this.filter,
required this.onFilterChanged,
required this.grid,
required this.onToggleGrid,
this.projects = const [],
this.selectedProjectId,
this.onProjectSelected,
});
final bool canImport;
final VoidCallback onImport;
final MediaFilter filter;
final ValueChanged<MediaFilter> onFilterChanged;
final bool grid;
final VoidCallback onToggleGrid;
final List<RecentProject> projects;
final String? selectedProjectId;
final ValueChanged<RecentProject>? onProjectSelected;
@override
State<MediaBrowserToolbar> createState() => _MediaBrowserToolbarState();
}
class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
Object? _filterConfiguration;
Widget? _filterControls;
bool get canImport => widget.canImport;
VoidCallback get onImport => widget.onImport;
MediaFilter get filter => widget.filter;
ValueChanged<MediaFilter> get onFilterChanged =>
(value) => widget.onFilterChanged(value);
bool get grid => widget.grid;
VoidCallback get onToggleGrid =>
() => widget.onToggleGrid();
List<RecentProject> get projects => widget.projects;
String? get selectedProjectId => widget.selectedProjectId;
ValueChanged<RecentProject>? get onProjectSelected =>
widget.onProjectSelected;
@override
Widget build(BuildContext context) {
final configuration = (
filter,
grid,
Theme.of(context),
Localizations.localeOf(context),
MediaQuery.textScalerOf(context),
Directionality.of(context),
);
if (_filterConfiguration != configuration) {
_filterConfiguration = configuration;
_filterControls = null;
}
final selected = projects
.where((project) => project.id == selectedProjectId)
.firstOrNull;
Widget row(Key key, Widget child) => SizedBox(
key: key,
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
),
child: child,
),
);
return Column(
key: const Key('media-panel-header'),
mainAxisSize: MainAxisSize.min,
children: [
row(
const Key('media-project-row'),
LayoutBuilder(
builder: (context, constraints) {
final painter = TextPainter(
text: TextSpan(
text: context.l10n.importMedia,
style: AppTheme.toolbarTextStyle(context),
),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
)..layout();
final compact = constraints.maxWidth < painter.width + 140;
painter.dispose();
return Row(
children: [
Expanded(
child: AppDropdownMenu(
enabled: onProjectSelected != null && projects.isNotEmpty,
maxHeight: 320,
items: [
for (final project in projects)
AppMenuItem(
key: ValueKey('media-project-${project.id}'),
label: project.name,
selected: project.id == selectedProjectId,
selectOption: true,
onPressed: onProjectSelected == null
? null
: () => onProjectSelected!(project),
),
],
builder: (context, toggle, focusNode) =>
AppToolbarDropdownButton(
buttonKey: const Key('media-project-button'),
focusNode: focusNode,
onPressed: toggle,
child: Row(
children: [
Expanded(
child: Text(
selected?.name ??
context.l10n.selectProject,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: AppSpacing.tiny),
const Icon(
Icons.keyboard_arrow_down,
size: AppIconSize.header,
),
],
),
),
),
),
const SizedBox(width: AppSpacing.tiny),
if (compact)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: canImport ? onImport : null,
icon: const Icon(Icons.add, size: AppIconSize.header),
),
)
else
SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(context),
onPressed: canImport ? onImport : null,
icon: const Icon(Icons.add, size: AppIconSize.header),
label: Text(context.l10n.importMedia),
),
),
],
);
},
),
),
_filterControls ??= row(
const Key('media-filter-row'),
Row(
children: [
Expanded(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: SizedBox(
width: 88,
height: AppControlSize.headerButton,
child: Semantics(
label: context.l10n.mediaCategory,
child: AppDropdownMenu(
items: [
for (final option in MediaFilter.values)
AppMenuItem(
label: option.label(context),
selected: option == filter,
selectOption: true,
onPressed: () => onFilterChanged(option),
),
],
builder: (context, toggle, focus) =>
AppToolbarDropdownButton(
buttonKey: const Key('media-category-button'),
focusNode: focus,
onPressed: toggle,
child: Row(
children: [
Expanded(
child: Text(
filter.label(context),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: AppSpacing.tiny),
const Icon(
Icons.keyboard_arrow_down,
size: AppIconSize.header,
),
],
),
),
),
),
),
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: onToggleGrid,
icon: Icon(
grid ? Icons.view_list_outlined : Icons.grid_view_outlined,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
),
),
],
);
}
}
+79 -114
View File
@@ -1,17 +1,19 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/projects.dart';
import '../../workspace/project_state.dart';
import '../../l10n/l10n.dart';
import 'media_browser_body.dart';
import 'media_browser_toolbar.dart';
import 'media_browser_controller.dart';
import 'media_browser_feedback.dart';
@@ -23,8 +25,10 @@ class MediaPanel extends ConsumerStatefulWidget {
this.backgroundColor,
this.grid,
this.onGridChanged,
this.onSelectProject,
}) : assert((grid == null) == (onGridChanged == null));
final String projectId;
final String? projectId;
final ValueChanged<RecentProject>? onSelectProject;
final Color? backgroundColor;
final bool? grid;
final ValueChanged<bool>? onGridChanged;
@@ -34,14 +38,70 @@ class MediaPanel extends ConsumerStatefulWidget {
class _MediaPanelState extends ConsumerState<MediaPanel> {
bool _hovering = false;
(String, bool)? _bodyConfiguration;
Widget? _body;
Widget _browserBody(String projectId, bool grid) {
final configuration = (projectId, grid);
if (_bodyConfiguration != configuration) {
_bodyConfiguration = configuration;
_body = MediaBrowserBody(
projectId: projectId,
grid: grid,
draggable: true,
compact: true,
);
}
return _body!;
}
@override
void didUpdateWidget(covariant MediaPanel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.projectId != widget.projectId) _hovering = false;
}
@override
Widget build(BuildContext context) {
ref.watch(projectsProvider);
final browser = ref.watch(mediaBrowserProvider(widget.projectId));
ref.watch(externalMediaImportProvider(widget.projectId));
final workspace = ref.watch(
projectsProvider.select(
(value) => (
value.value?.recent ?? const <RecentProject>[],
value.value?.projectBusy ?? false,
value.value?.activeProject?.id,
),
),
);
final projectId = widget.projectId;
final onSelectProject = workspace.$2 ? null : widget.onSelectProject;
if (projectId == null) {
return Material(
key: const Key('media-panel-surface'),
color: widget.backgroundColor ?? Colors.transparent,
child: Column(
children: [
MediaBrowserToolbar(
projects: workspace.$1,
onProjectSelected: onSelectProject,
canImport: false,
onImport: () {},
filter: MediaFilter.all,
onFilterChanged: (_) {},
grid: true,
onToggleGrid: () {},
),
Expanded(child: Center(child: Text(context.l10n.selectProject))),
],
),
);
}
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableBuilder(
return ListenableSelector(
listenable: browser,
select: () =>
(browser.filter, browser.grid, browser.busy, browser.canImport),
builder: (context, _) {
final grid = widget.grid ?? browser.grid;
final visible =
@@ -61,121 +121,26 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
feedback: browser.feedback,
child: Material(
key: const Key('media-panel-surface'),
color: widget.backgroundColor,
color: widget.backgroundColor ?? Colors.transparent,
child: Stack(
fit: StackFit.expand,
children: [
Column(
children: [
SizedBox(
key: const Key('media-panel-header'),
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.all(AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxWidth < 180;
final controls = Row(
mainAxisSize: compact
? MainAxisSize.min
: MainAxisSize.max,
children: [
if (compact)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
),
)
else
SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(
context,
),
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
label: Text(context.l10n.importMedia),
),
),
if (compact)
const SizedBox(width: AppSpacing.tiny)
else
const Spacer(),
SizedBox(
width: 76,
child: AppSelect<MediaFilter>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.mediaCategory,
outlined: false,
controlHeight: AppControlSize.headerButton,
textStyle: AppTheme.toolbarTextStyle(
context,
),
value: browser.filter,
onChanged: (value) =>
browser.filter = value,
options: [
for (final filter in MediaFilter.values)
AppSelectOption(
filter,
filter.label(context),
),
],
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: toggleGrid,
icon: Icon(
grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
);
return compact
? SingleChildScrollView(
key: const Key('media-header-scroll'),
scrollDirection: Axis.horizontal,
child: controls,
)
: controls;
},
),
),
MediaBrowserToolbar(
projects: workspace.$1,
selectedProjectId: projectId,
onProjectSelected: onSelectProject,
canImport: enabled,
onImport: () => pickMediaFiles(browser),
filter: browser.filter,
onFilterChanged: (value) => browser.filter = value,
grid: grid,
onToggleGrid: toggleGrid,
),
Expanded(
key: const Key('media-panel-body'),
child: MediaBrowserBody(
projectId: widget.projectId,
grid: grid,
draggable: true,
),
child: _browserBody(projectId, grid),
),
],
),
+420 -304
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../diagnostics/app_diagnostics.dart';
import 'dart:async';
@@ -17,6 +19,7 @@ import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/preview_controller_registry.dart';
import '../../workspace/preview_target.dart';
@@ -148,13 +151,19 @@ class EditorPreviewPanel extends StatelessWidget {
super.key,
required this.projectId,
required this.timelineId,
this.pending = false,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context) => PreviewFullscreenHost(
child: _EditorPreviewContent(projectId: projectId, timelineId: timelineId),
child: _EditorPreviewContent(
projectId: projectId,
timelineId: timelineId,
pending: pending,
),
);
}
@@ -162,199 +171,256 @@ class _EditorPreviewContent extends ConsumerWidget {
const _EditorPreviewContent({
required this.projectId,
required this.timelineId,
this.pending = false,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = editorPreviewProvider(projectId, timelineId);
final state = ref.watch(provider);
final watched = pending
? const AsyncData<PreviewController?>(null)
: ref.watch(provider);
final cached = watched.isLoading && !watched.hasError
? ref.read(previewControllerRegistryProvider).cached((
projectId,
timelineId,
))
: null;
final state = cached == null
? watched
: AsyncData<PreviewController?>(cached);
final controller = state.asData?.value;
Widget panel() {
final activeController = controller;
final showCanvas =
state.hasError ||
(activeController != null &&
(activeController.durationTick > 0 ||
activeController.error != null));
final overlayBuilder =
activeController != null &&
PreviewFullscreenScope.of(context)?.fullscreen != true &&
activeController.session != null &&
activeController.error == null
? (Rect rect) => ListenableBuilder(
listenable: activeController.positionChanges,
builder: (context, _) => Theme(
data: AppTheme.previewCanvasTheme,
child:
activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null
? MaskInteractionOverlay(
controller: activeController,
canvasRect: rect,
obscure: activeController.obscureEditingElement != null,
)
: PreviewInteractionOverlay(
onError: (_) => ScaffoldMessenger.maybeOf(context)
?.showSnackBar(
SnackBar(
content: Text(
context.l10n.canvasTransformFailed,
),
),
),
controller: activeController,
canvasRect: rect,
),
),
)
: null;
return WorkspacePanel(
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: showCanvas
? Padding(
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppSpacing.panelSection,
child: PreviewCanvas(
alignment: Alignment.center,
horizontalPadding: 0,
backgroundColor: AppSurfaces.of(context).previewBackground,
overlayBuilder: overlayBuilder,
aspectRatio:
(activeController?.canvas ?? ProjectCanvas.widescreen)
.aspectRatio,
child: Theme(
Widget panel() => WorkspacePanel(
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: controller,
select: () => (
controller?.canvas,
controller?.session,
controller?.error,
(controller?.durationTick ?? 0) > 0,
),
builder: (context, _) {
final activeController = controller;
final defaultCanvas =
pending ||
(state.isLoading && !state.hasError && controller == null);
final showCanvas =
defaultCanvas ||
state.hasError ||
(activeController != null &&
(activeController.durationTick > 0 ||
activeController.error != null));
final overlayBuilder =
activeController != null &&
PreviewFullscreenScope.of(context)?.fullscreen != true &&
activeController.session != null &&
activeController.error == null
? (Rect rect) => ListenableBuilder(
listenable: activeController.positionChanges,
builder: (context, _) => Theme(
data: AppTheme.previewCanvasTheme,
child: Builder(
builder: (context) => state.when(
loading: () => const DelayedLoadingIndicator(
child: Center(child: CircularProgressIndicator()),
),
error: (error, _) => Center(
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
error is EditorSessionStartupException
? context.l10n.editorSessionStartFailed
: error is RuntimeException &&
error.code == 'unsupported'
? context.l10n.nativePreviewUnsupported
: context.l10n.previewStartFailed,
textAlign: TextAlign.center,
child:
activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null
? MaskInteractionOverlay(
controller: activeController,
canvasRect: rect,
obscure:
activeController.obscureEditingElement !=
null,
)
: PreviewInteractionOverlay(
onError: (error) =>
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(
context.l10n.canvasTransformFailed,
),
details: error.toString(),
),
),
TextButton(
onPressed: () {
if (error
is EditorSessionStartupException) {
ref.invalidate(
editorTimelineProvider(
projectId,
timelineId,
),
);
} else {
unawaited(
ref
.read(
previewControllerRegistryProvider,
)
.invalidate((
projectId,
timelineId,
)),
);
ref.invalidate(provider);
}
},
child: Text(context.l10n.retry),
),
],
),
controller: activeController,
canvasRect: rect,
),
),
data: (preview) {
if (preview == null) {
return const SizedBox.expand(
key: Key('empty-preview-area'),
);
}
return Stack(
fit: StackFit.expand,
children: [
if (preview.session case final session?)
RuntimePreview(session: session),
ListenableBuilder(
listenable: preview.positionChanges,
builder: (context, _) {
final unavailable =
preview.unavailableAtPlayhead;
if (preview.error != null ||
unavailable.isEmpty) {
return const SizedBox.shrink();
}
return IgnorePointer(
child: Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.medium,
),
child: Text(
context.l10n.mediaOffline(
unavailable.join(', '),
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
)
: null;
return showCanvas
? Padding(
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppSpacing.panelSection,
child: PreviewCanvas(
alignment: Alignment.center,
horizontalPadding: 0,
backgroundColor: AppSurfaces.of(context)
.previewBackground,
overlayBuilder: overlayBuilder,
aspectRatio:
(activeController?.canvas ?? ProjectCanvas.widescreen)
.aspectRatio,
child: Theme(
data: AppTheme.previewCanvasTheme,
child: Builder(
builder: (context) => defaultCanvas
? const ColoredBox(
key: Key('preview-default-frame'),
color: Colors.black,
)
: state.when(
skipLoadingOnReload: true,
loading: () => const ColoredBox(
key: Key('preview-default-frame'),
color: Colors.black,
),
error: (error, _) => Center(
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
error is EditorSessionStartupException
? context
.l10n
.editorSessionStartFailed
: error is RuntimeException &&
error.code ==
'unsupported'
? context
.l10n
.nativePreviewUnsupported
: context.l10n.previewStartFailed,
textAlign: TextAlign.center,
),
),
),
);
},
),
if (preview.error != null ||
preview.durationTick == 0)
ColoredBox(
color: AppSurfaces.of(context)
.previewBackground,
child: Center(
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.medium,
),
child: Text(
preview.error == null
? context.l10n.noPreviewContent
: previewErrorMessage(
preview.error!,
context.l10n,
),
textAlign: TextAlign.center,
),
TextButton(
onPressed: () {
if (error
is EditorSessionStartupException) {
ref.invalidate(
editorTimelineProvider(
projectId,
timelineId,
),
);
} else {
unawaited(
ref
.read(
previewControllerRegistryProvider,
)
.invalidate((
projectId,
timelineId,
)),
);
ref.invalidate(provider);
}
},
child: Text(context.l10n.retry),
),
],
),
),
),
],
);
},
data: (preview) {
if (preview == null) {
return const SizedBox.expand(
key: Key('empty-preview-area'),
);
}
return Stack(
fit: StackFit.expand,
children: [
if (preview.session case final session?)
RuntimePreview(session: session),
ListenableSelector(
listenable: Listenable.merge([
preview,
preview.positionChanges,
]),
select: () => (
preview.error,
preview.unavailableAtPlayhead.join(
', ',
),
),
builder: (context, _) {
final unavailable =
preview.unavailableAtPlayhead;
if (preview.error != null ||
unavailable.isEmpty) {
return const SizedBox.shrink();
}
return IgnorePointer(
child: Align(
alignment:
Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.medium,
),
child: Text(
context.l10n.mediaOffline(
unavailable.join(', '),
),
maxLines: 2,
overflow:
TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
),
),
);
},
),
if (preview.error != null ||
preview.durationTick == 0)
ColoredBox(
color: AppSurfaces.of(context)
.previewBackground,
child: Center(
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.medium,
),
child: Text(
preview.error == null
? context
.l10n
.noPreviewContent
: previewErrorMessage(
preview.error!,
context.l10n,
),
textAlign: TextAlign.center,
),
),
),
),
],
);
},
),
),
),
),
),
)
: const SizedBox.expand(key: Key('empty-preview-area')),
toolbar: _PreviewToolbar(controller: controller),
)
: const SizedBox.expand(key: Key('empty-preview-area'));
},
),
);
}
toolbar: _PreviewToolbar(controller: controller),
),
);
if (pending) return panel();
final target = ref.watch(previewTargetProvider(projectId, timelineId));
final navigation = ref.watch(
@@ -381,12 +447,7 @@ class _EditorPreviewContent extends ConsumerWidget {
target.togglePlayback = controller == null
? null
: () => unawaited(controller.togglePlayback());
return controller == null
? panel()
: ListenableBuilder(
listenable: controller,
builder: (_, _) => panel(),
);
return panel();
},
),
},
@@ -410,34 +471,40 @@ class _SourcePreviewPanel extends ConsumerWidget {
.watch(mediaAvailabilityProvider(projectId, asset))
.asData
?.value;
return ListenableBuilder(
listenable: source,
builder: (context, _) {
// The availability probe can finish while a newly dropped file is
// still switching security-scoped leases. Once the runtime has opened
// the source, that live session is stronger evidence than the stale
// probe result and must not be covered by an unavailable placeholder.
final unavailable =
availability != null &&
availability != MediaAvailability.available &&
source.session == null &&
source.image == null;
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.space):
source.togglePlayback,
},
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: asset.name,
showHeaderDivider: false,
headerHeight:
PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
canvas: Padding(
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.space): source.togglePlayback,
},
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: asset.name,
showHeaderDivider: false,
headerHeight: PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: source,
select: () => (
source.session,
source.image,
source.error,
source.busy,
source.aspectRatio,
source.audioOnly,
),
builder: (context, _) {
// The availability probe can finish while a newly dropped file is
// still switching security-scoped leases. Once the runtime has opened
// the source, that live session is stronger evidence than the stale
// probe result and must not be covered by an unavailable placeholder.
final unavailable =
availability != null &&
availability != MediaAvailability.available &&
source.session == null &&
source.image == null;
return Padding(
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
@@ -508,13 +575,13 @@ class _SourcePreviewPanel extends ConsumerWidget {
),
),
),
),
toolbar: _PreviewToolbar(controller: null, source: source),
),
);
},
),
toolbar: _PreviewToolbar(controller: null, source: source),
),
);
},
),
),
);
}
}
@@ -527,18 +594,33 @@ class _PreviewToolbar extends StatelessWidget {
@override
Widget build(BuildContext context) {
final listenable = source == null && controller != null
? Listenable.merge([controller!, controller!.positionChanges])
: source;
if (listenable != null) {
return ListenableBuilder(
listenable: listenable,
if (PreviewFullscreenScope.of(context)?.fullscreen == true) {
return ListenableSelector(
listenable: _clock,
select: () => (
source?.positionTick ?? controller?.positionTick ?? 0,
source?.durationTick ?? controller?.durationTick ?? 0,
source?.frameDuration ?? controller?.frameDuration,
source?.playing ?? controller?.playing ?? false,
source?.canPlay ?? controller?.canPlay ?? false,
),
builder: (context, _) => _build(context),
);
}
return _build(context);
}
Listenable? get _clock =>
source ??
(controller == null
? null
: Listenable.merge([controller!, controller!.positionChanges]));
RationalTime get _frameDuration =>
source?.frameDuration ??
controller?.frameDuration ??
TimelineFormat.fps30.frameDuration;
Widget _build(BuildContext context) {
final preview = controller;
final playing = source?.playing ?? preview?.playing ?? false;
@@ -569,8 +651,10 @@ class _PreviewToolbar extends StatelessWidget {
}
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(content: Text(previewErrorMessage(error, context.l10n))),
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
);
}
}
@@ -618,96 +702,128 @@ class _PreviewToolbar extends StatelessWidget {
child: Row(
children: [
Expanded(
child: Text.rich(
TextSpan(
children: [
TextSpan(
text: _time(
source?.positionTick ?? preview?.positionTick ?? 0,
frameDuration,
),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
TextSpan(
text:
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, frameDuration)}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
child: ListenableSelector(
key: const Key('preview-time'),
listenable: _clock,
select: () => (
source?.positionTick ?? preview?.positionTick ?? 0,
source?.durationTick ?? preview?.durationTick ?? 0,
_frameDuration,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFeatures: [const FontFeature.tabularFigures()],
builder: (context, _) => Text.rich(
TextSpan(
children: [
TextSpan(
text: _time(
source?.positionTick ?? preview?.positionTick ?? 0,
_frameDuration,
),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
TextSpan(
text:
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, _frameDuration)}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFeatures: [const FontFeature.tabularFigures()],
),
),
),
),
IconButton(
tooltip: playing ? context.l10n.pause : context.l10n.play,
onPressed: source != null
? (source!.canPlay ? source!.togglePlayback : null)
: preview != null && preview.canPlay
? preview.togglePlayback
: null,
icon: Icon(playing ? Icons.pause : Icons.play_arrow),
ListenableSelector(
listenable: source ?? preview,
select: () => (
source?.playing ?? preview?.playing ?? false,
source?.canPlay ?? preview?.canPlay ?? false,
),
builder: (context, value) {
final playing = value.$1;
return IconButton(
tooltip: playing ? context.l10n.pause : context.l10n.play,
onPressed: source != null
? (source!.canPlay ? source!.togglePlayback : null)
: preview != null && preview.canPlay
? preview.togglePlayback
: null,
icon: Icon(playing ? Icons.pause : Icons.play_arrow),
);
},
),
Expanded(
child: Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (preview != null &&
(preview.error != null ||
preview.hasUnavailableMedia)) ...[
IconButton(
tooltip: context.l10n.retryPreview,
onPressed: preview.busy ? null : preview.retry,
icon: const Icon(Icons.refresh),
),
const SizedBox(width: AppSpacing.gap),
child: ListenableSelector(
listenable: source ?? preview,
select: () => (
preview?.canvas,
preview?.error,
preview?.hasUnavailableMedia,
preview?.busy,
preview?.session,
source?.session,
source?.image,
),
builder: (context, _) => Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (preview != null &&
(preview.error != null ||
preview.hasUnavailableMedia)) ...[
IconButton(
tooltip: context.l10n.retryPreview,
onPressed: preview.busy ? null : preview.retry,
icon: const Icon(Icons.refresh),
),
const SizedBox(width: AppSpacing.gap),
],
if (source == null &&
PreviewFullscreenScope.of(context)?.fullscreen !=
true)
Flexible(
child: AppSelect<ProjectCanvas>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.canvasRatio,
outlined: false,
value: preview?.canvas ?? ProjectCanvas.widescreen,
onChanged: preview?.setCanvas,
options: [
for (final entry
in ProjectCanvasPresets.values.entries)
AppSelectOption(entry.value, entry.key),
],
),
),
if (PreviewFullscreenScope.of(context)
case final fullscreen?)
IconButton(
key: const Key('preview-fullscreen'),
tooltip: fullscreen.fullscreen
? context.l10n.exitPreviewFullscreen
: context.l10n.previewFullscreen,
onPressed:
fullscreen.fullscreen ||
source?.session != null ||
source?.image != null ||
preview?.session != null
? fullscreen.toggle
: null,
icon: Icon(
fullscreen.fullscreen
? Icons.fullscreen_exit
: Icons.fullscreen,
),
),
],
if (source == null &&
PreviewFullscreenScope.of(context)?.fullscreen != true)
Flexible(
child: AppSelect<ProjectCanvas>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.canvasRatio,
outlined: false,
value: preview?.canvas ?? ProjectCanvas.widescreen,
onChanged: preview?.setCanvas,
options: [
for (final entry
in ProjectCanvasPresets.values.entries)
AppSelectOption(entry.value, entry.key),
],
),
),
if (PreviewFullscreenScope.of(context)
case final fullscreen?)
IconButton(
key: const Key('preview-fullscreen'),
tooltip: fullscreen.fullscreen
? context.l10n.exitPreviewFullscreen
: context.l10n.previewFullscreen,
onPressed:
fullscreen.fullscreen ||
source?.session != null ||
source?.image != null ||
preview?.session != null
? fullscreen.toggle
: null,
icon: Icon(
fullscreen.fullscreen
? Icons.fullscreen_exit
: Icons.fullscreen,
),
),
],
),
),
),
),
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -97,17 +99,72 @@ class ConversationSidebar extends _$ConversationSidebar {
@override
Future<ConversationSnapshot> build() async {
ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id),
(before, after) {
if (before != after) unawaited(_refreshContext(after));
},
);
await ref.watch(
projectsProvider.selectAsync(
(workspace) => ConversationWorkspaceKey(
projectId: workspace.activeProject?.id,
projectIds: [for (final project in workspace.recent) project.id],
),
),
);
_revision++;
final workspace = ref.read(projectsProvider).requireValue;
return _load(workspace);
final loaded = await _load(workspace);
if (!ref.mounted) return loaded;
final activeId = ref.read(projectsProvider).value?.activeProject?.id;
return activeId == loaded.projectId
? loaded
: _loadContext(loaded, activeId);
}
/// Project selection changes only contextual data, never the global groups.
Future<ConversationSnapshot> _loadContext(
ConversationSnapshot current,
String? projectId,
) async {
final repository = await ref.read(conversationRepositoryProvider.future);
final trashed = projectId == null
? const <ConversationMetadata>[]
: await repository.list(projectId, trash: true);
final selectedId = await ref.read(
savedConversationSelectionProvider(projectId).future,
);
return current.copyWith(
projectId: projectId,
trashed: List.unmodifiable(trashed),
selectedId: selectedId,
reloadFailed: false,
);
}
Future<void> _refreshContext(String? projectId) async {
final current = state.value;
if (current == null) return; // Initial loading resolves the latest context.
final revision = ++_revision;
state = AsyncData(
current.copyWith(
projectId: projectId,
trashed: const [],
selectedId: null,
),
);
try {
final next = await _loadContext(current, projectId);
if (ref.mounted &&
revision == _revision &&
ref.read(projectsProvider).value?.activeProject?.id == projectId) {
state = AsyncData(next);
}
} catch (_) {
if (ref.mounted && revision == _revision) {
state = AsyncData(state.requireValue.copyWith(reloadFailed: true));
}
}
}
Future<ConversationSnapshot> _load(ProjectState workspace) async {
@@ -220,7 +220,7 @@ final class ConversationSidebarProvider
}
String _$conversationSidebarHash() =>
r'13122a844ce87622c8d4919042e4dbefc69b790f';
r'ccb6d44f3c675b664a0e0925f9257b351061a899';
abstract class _$ConversationSidebar
extends $AsyncNotifier<ConversationSnapshot> {
@@ -5,7 +5,6 @@ import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
class EmptyEditor extends StatelessWidget {
const EmptyEditor({
@@ -13,32 +12,44 @@ class EmptyEditor extends StatelessWidget {
required this.state,
required this.headerLeading,
required this.showProjectName,
this.desktop = false,
});
final ProjectState state;
final Widget headerLeading;
final bool showProjectName;
final bool desktop;
@override
Widget build(BuildContext context) => Column(
children: [
SizedBox(
height: AppControlSize.panelHeader,
child: WindowHeaderPadding(
child: Row(
children: [
headerLeading,
if (showProjectName)
Expanded(
child: Text(
state.activeProject?.name ?? '',
key: const Key('workspace-project-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
height: desktop
? AppControlSize.panelToolbar
: AppControlSize.panelHeader,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding(
child: Row(
children: [
headerLeading,
if (showProjectName)
Expanded(
child: Text(
state.activeProject?.name ?? '',
key: const Key('workspace-project-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
),
),
),
],
],
),
),
),
),
@@ -77,40 +88,3 @@ class EmptyEditor extends StatelessWidget {
],
);
}
class ProjectLoadingRegion extends StatelessWidget {
const ProjectLoadingRegion({
super.key,
required this.loading,
required this.child,
});
final bool loading;
final Widget child;
@override
Widget build(BuildContext context) => Stack(
fit: StackFit.expand,
children: [
ExcludeFocus(
excluding: loading,
child: IgnorePointer(ignoring: loading, child: child),
),
if (loading)
DelayedLoadingIndicator(
child: Positioned.fill(
child: ColoredBox(
key: const Key('editor-project-loading'),
color: Theme.of(context).colorScheme.surface,
child: const Center(
child: SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
),
),
),
],
);
}
+400 -276
View File
@@ -1,5 +1,8 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../integrations/platform/device_experience.dart';
import 'touch_project_navigation.dart';
import '../media/media_panel.dart';
import 'package:cutdex_ui/theme.dart';
@@ -8,6 +11,9 @@ import 'dart:async';
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import '../../shared/widgets/listenable_selector.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/editor_window_chrome.dart';
@@ -38,6 +44,8 @@ class ProjectSidebar extends ConsumerStatefulWidget {
super.key,
required this.agent,
this.navigationOnly = false,
this.resourcesSelected = false,
this.externalWindowFrame = false,
this.experience = DeviceExperience.desktop,
this.onNavigationComplete,
required this.mode,
@@ -58,6 +66,8 @@ class ProjectSidebar extends ConsumerStatefulWidget {
final Widget agent;
final bool navigationOnly;
final bool resourcesSelected;
final bool externalWindowFrame;
final DeviceExperience experience;
final VoidCallback? onNavigationComplete;
final ProjectState state;
@@ -80,6 +90,7 @@ class ProjectSidebar extends ConsumerStatefulWidget {
}
class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
bool _resourcesVisited = false;
bool get _touch => widget.experience != DeviceExperience.desktop;
bool _projectHeaderHovered = false;
String? _hoveredProjectId;
@@ -87,6 +98,30 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
final Set<String> _expandedConversationProjects = {};
final Set<String> _collapsedProjects = {};
bool _showTrash = false;
late final ValueNotifier<String?> _projectSelection;
final _groupWidgets = <String, (Object, Widget)>{};
@override
void initState() {
super.initState();
_resourcesVisited = widget.resourcesSelected;
_projectSelection = ValueNotifier(widget.selectedProjectId);
}
@override
void didUpdateWidget(covariant ProjectSidebar oldWidget) {
super.didUpdateWidget(oldWidget);
_resourcesVisited |= widget.resourcesSelected;
_projectSelection.value = widget.selectedProjectId;
final ids = widget.state.recent.map((project) => project.id).toSet();
_groupWidgets.removeWhere((id, _) => !ids.contains(id));
}
@override
void dispose() {
_projectSelection.dispose();
super.dispose();
}
ConversationSidebar get _conversations =>
ref.read(conversationSidebarProvider.notifier);
@@ -98,11 +133,8 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
}
Map<String, List<ConversationMetadata>> get _conversationsByProject =>
_snapshot.groups;
ref.read(conversationSidebarProvider).value?.groups ?? const {};
List<ConversationMetadata> get _trashed => _snapshot.trashed;
String? get _selectedConversationId => ref
.read(conversationSelectionProvider(widget.state.activeProject?.id))
.selectedId;
String? get _conversationError =>
(ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed)
? context.l10n.agentSessionRestoreFailed
@@ -253,9 +285,9 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
await _conversations.delete(item);
} catch (_) {
if (mounted) {
ScaffoldMessenger.of(
ErrorNotificationHost.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.operationFailed)));
).show(ErrorNotification(content: Text(context.l10n.operationFailed)));
}
}
}
@@ -293,74 +325,84 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
) ==
true;
Widget _conversationRow(ConversationMetadata item) {
final selected =
widget.state.activeProject?.id == item.projectId &&
_selectedConversationId == item.id;
List<Widget> actions(BuildContext context) => [
AppMenuItem(
label: context.l10n.rename,
onPressed: () => _renameConversation(item),
),
AppMenuItem(
label: context.l10n.agentMoveToTrash,
onPressed: () => _trashConversation(item),
),
AppMenuItem(
label: context.l10n.agentRelinkProvider,
onPressed: () => _relinkProvider(item),
),
const AppMenuSeparator(),
AppMenuItem(
label: '${context.l10n.agentDeleteForever}…',
destructive: true,
onPressed: () => _deleteForever(item),
),
];
if (_touch) {
return TouchConversationTile(
id: item.id,
title: item.title,
selected: selected,
onSelect: () => _selectConversation(item),
actions: actions,
Widget _conversationRow(ConversationMetadata item) => Consumer(
builder: (context, ref, _) {
final active = ref.watch(
projectsProvider.select(
(value) => value.value?.activeProject?.id == item.projectId,
),
);
}
return Padding(
padding: AppSidebarMetrics.rowPadding,
child: AppContextMenu(
itemsBuilder: actions,
child: Material(
color: selected
? AppSidebarColors.of(context).hover
: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
child: InkWell(
key: ValueKey('sidebar-conversation-${item.id}'),
hoverColor: selected
? Colors.transparent
: AppSidebarColors.of(context).hover,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
final selected =
ref.watch(
conversationSelectionProvider(item.projectId)
.select((value) => value.selectedId == item.id),
) &&
active;
List<Widget> actions(BuildContext context) => [
AppMenuItem(
label: context.l10n.rename,
onPressed: () => _renameConversation(item),
),
AppMenuItem(
label: context.l10n.agentMoveToTrash,
onPressed: () => _trashConversation(item),
),
AppMenuItem(
label: context.l10n.agentRelinkProvider,
onPressed: () => _relinkProvider(item),
),
const AppMenuSeparator(),
AppMenuItem(
label: '${context.l10n.agentDeleteForever}…',
destructive: true,
onPressed: () => _deleteForever(item),
),
];
if (_touch) {
return TouchConversationTile(
id: item.id,
title: item.title,
selected: selected,
onSelect: () => _selectConversation(item),
actions: actions,
);
}
return Padding(
padding: AppSidebarMetrics.rowPadding,
child: AppContextMenu(
itemsBuilder: actions,
child: Material(
color: selected
? AppSidebarColors.of(context).hover
: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
onTap: () => _selectConversation(item),
child: SizedBox(
height: AppSidebarMetrics.rowHeight,
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: AppSidebarMetrics.textInset,
end: AppSidebarMetrics.cellPadding,
),
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.conversationFontSize,
height: AppSidebarMetrics.conversationLineHeight,
child: InkWell(
key: ValueKey('sidebar-conversation-${item.id}'),
hoverColor: selected
? Colors.transparent
: AppSidebarColors.of(context).hover,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
onTap: () => _selectConversation(item),
child: SizedBox(
height: AppSidebarMetrics.rowHeight,
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: AppSidebarMetrics.textInset,
end: AppSidebarMetrics.cellPadding,
),
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.conversationFontSize,
height: AppSidebarMetrics.conversationLineHeight,
),
),
),
),
@@ -368,11 +410,39 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
),
),
),
),
);
}
);
},
);
Widget _projectGroup(RecentProject project) {
final configuration = (
project,
_touch,
Localizations.localeOf(context),
Theme.of(context),
_expandedConversationProjects.contains(project.id),
_collapsedProjects.contains(project.id),
_hoveredProjectId == project.id,
widget.state.projectBusy,
);
final cached = _groupWidgets[project.id];
if (cached?.$1 == configuration) return cached!.$2;
final group = Consumer(
key: ValueKey('sidebar-project-binding-${project.id}'),
builder: (context, ref, _) {
ref.watch(
conversationSidebarProvider.select(
(value) => value.value?.groups[project.id],
),
);
return _buildProjectGroup(project);
},
);
_groupWidgets[project.id] = (configuration, group);
return group;
}
Widget _buildProjectGroup(RecentProject project) {
final conversations = _conversationsByProject[project.id] ?? const [];
final expanded = _expandedConversationProjects.contains(project.id);
final collapsed = _collapsedProjects.contains(project.id);
@@ -382,6 +452,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
? conversations
: conversations.take(5);
return Column(
key: ValueKey('sidebar-project-group-${project.id}'),
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
MouseRegion(
@@ -391,65 +462,70 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
setState(() => _hoveredProjectId = null);
}
},
child: _touch
? TouchProjectTile(
project: project,
selected: widget.selectedProjectId == project.id,
expanded: !collapsed,
availabilityLabel: _availabilityLabel(
context,
project.availability,
),
onSelect: () => _selectProjectFromNavigation(project),
onToggle: () => setState(() {
if (collapsed) {
_collapsedProjects.remove(project.id);
} else {
_collapsedProjects.add(project.id);
}
}),
onNewConversation:
widget.state.projectBusy || !project.availability.canOpen
? null
: () => _newConversationForProject(project),
onRename: project.availability.canOpen
? () => widget.onRenameProject(project)
: null,
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
)
: Padding(
padding: AppSidebarMetrics.rowPadding,
child: _ProjectTile(
child: ListenableSelector(
listenable: _projectSelection,
select: () => _projectSelection.value == project.id,
builder: (context, selected) => _touch
? TouchProjectTile(
project: project,
active: widget.selectedProjectId == project.id,
selected: selected,
expanded: !collapsed,
availabilityLabel: _availabilityLabel(
context,
project.availability,
),
onSelect: () {
_cutProjectsMenu.close();
_selectProjectFromNavigation(project);
},
onRename: () => widget.onRenameProject(project),
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
expanded: !collapsed,
onToggleExpanded: () => setState(() {
onSelect: () => _selectProjectFromNavigation(project),
onToggle: () => setState(() {
if (collapsed) {
_collapsedProjects.remove(project.id);
} else {
_collapsedProjects.add(project.id);
}
}),
sidebarStyle: true,
hovered: _hoveredProjectId == project.id,
onNewConversation: () =>
_newConversationForProject(project),
onNewConversation:
widget.state.projectBusy ||
!project.availability.canOpen
? null
: () => _newConversationForProject(project),
onRename: project.availability.canOpen
? () => widget.onRenameProject(project)
: null,
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
)
: Padding(
padding: AppSidebarMetrics.rowPadding,
child: _ProjectTile(
project: project,
active: selected,
availabilityLabel: _availabilityLabel(
context,
project.availability,
),
onSelect: () {
_cutProjectsMenu.close();
_selectProjectFromNavigation(project);
},
onRename: () => widget.onRenameProject(project),
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
expanded: !collapsed,
onToggleExpanded: () => setState(() {
if (collapsed) {
_collapsedProjects.remove(project.id);
} else {
_collapsedProjects.add(project.id);
}
}),
sidebarStyle: true,
hovered: _hoveredProjectId == project.id,
onNewConversation: () =>
_newConversationForProject(project),
),
),
),
),
),
for (final item in visible) ...[
const SizedBox(height: AppSidebarMetrics.rowGap),
@@ -516,18 +592,21 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
@override
Widget build(BuildContext context) {
ref.watch(conversationSidebarProvider);
ref.watch(conversationSelectionProvider(widget.state.activeProject?.id));
final compact = MediaQuery.sizeOf(context).height < 520;
final headerHeight = widget.navigationOnly
final headerHeight = widget.externalWindowFrame
? 0.0
: widget.navigationOnly
? 48.0
: widget.integratedTitlebar
? AppControlSize.panelHeader
: AppControlSize.headerButton;
final modeTop = headerHeight;
final modeHeader = SizedBox(
key: const Key('project-content-header'),
height:
modeTop + AppSidebarMetrics.modeHeight + AppSidebarMetrics.sectionGap,
modeTop +
(_touch ? AppSidebarMetrics.modeHeight : 0) +
(widget.externalWindowFrame ? 0 : AppSidebarMetrics.sectionGap),
child: Stack(
children: [
Positioned(
@@ -554,94 +633,95 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
),
),
),
Positioned(
top: modeTop,
left: AppSidebarMetrics.outerPadding,
right: AppSidebarMetrics.outerPadding,
height: AppSidebarMetrics.modeHeight,
child: Align(
alignment: AlignmentDirectional.topStart,
child: AppPopover(
width: AppMenuMetrics.modeMenuWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final mode in WorkspaceMode.values)
AppMenuItem(
key: ValueKey('sidebar-mode-${mode.name}'),
label: mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
selected: widget.mode == mode,
description: mode == WorkspaceMode.agent
? context.l10n.agentLayoutDescription
: context.l10n.editingLayoutDescription,
onPressed: () {
widget.onModeChanged(mode);
if (widget.navigationOnly) _finishNavigation();
},
),
],
),
builder: (context, toggle) => TextButton(
key: const Key('sidebar-mode-trigger'),
onPressed: toggle,
style: ButtonStyle(
foregroundColor: sidebarActionButtonStyle(context)
.foregroundColor,
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 8),
),
minimumSize: const WidgetStatePropertyAll(
Size(0, AppSidebarMetrics.modeHeight),
),
alignment: AlignmentDirectional.centerStart,
backgroundColor: WidgetStateProperty.resolveWith(
(states) =>
states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)
? AppSidebarColors.of(context).hover
: Colors.transparent,
),
overlayColor: const WidgetStatePropertyAll(
Colors.transparent,
),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
child: Row(
if (_touch)
Positioned(
top: modeTop,
left: AppSidebarMetrics.outerPadding,
right: AppSidebarMetrics.outerPadding,
height: AppSidebarMetrics.modeHeight,
child: Align(
alignment: AlignmentDirectional.topStart,
child: AppPopover(
width: AppMenuMetrics.modeMenuWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
widget.mode == WorkspaceMode.agent
for (final mode in WorkspaceMode.values)
AppMenuItem(
key: ValueKey('sidebar-mode-${mode.name}'),
label: mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.titleFontSize,
height: AppSidebarMetrics.titleLineHeight,
weight: FontWeight.w600,
),
selected: widget.mode == mode,
description: mode == WorkspaceMode.agent
? context.l10n.agentLayoutDescription
: context.l10n.editingLayoutDescription,
onPressed: () {
widget.onModeChanged(mode);
if (widget.navigationOnly) _finishNavigation();
},
),
],
),
builder: (context, toggle) => TextButton(
key: const Key('sidebar-mode-trigger'),
onPressed: toggle,
style: ButtonStyle(
foregroundColor: sidebarActionButtonStyle(context)
.foregroundColor,
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 8),
),
minimumSize: const WidgetStatePropertyAll(
Size(0, AppSidebarMetrics.modeHeight),
),
alignment: AlignmentDirectional.centerStart,
backgroundColor: WidgetStateProperty.resolveWith(
(states) =>
states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)
? AppSidebarColors.of(context).hover
: Colors.transparent,
),
overlayColor: const WidgetStatePropertyAll(
Colors.transparent,
),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
const SizedBox(width: AppSpacing.small),
const Icon(
Icons.keyboard_arrow_down,
size: AppSidebarMetrics.iconSize,
),
],
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
widget.mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.titleFontSize,
height: AppSidebarMetrics.titleLineHeight,
weight: FontWeight.w600,
),
),
),
const SizedBox(width: AppSpacing.small),
const Icon(
Icons.keyboard_arrow_down,
size: AppSidebarMetrics.iconSize,
),
],
),
),
),
),
),
),
],
),
);
@@ -656,9 +736,9 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
onEnter: (_) => setState(() => _projectHeaderHovered = true),
onExit: (_) => setState(() => _projectHeaderHovered = false),
child: Padding(
padding: const EdgeInsets.fromLTRB(
padding: EdgeInsets.fromLTRB(
AppSidebarMetrics.outerPadding,
0,
_touch ? 0 : AppSpacing.gap,
AppSidebarMetrics.outerPadding,
AppSidebarMetrics.sectionGap,
),
@@ -692,79 +772,102 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap),
_projectGroup(widget.state.recent[index]),
],
if (_conversationError != null)
Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
_conversationError!,
style: Theme.of(context).textTheme.bodySmall,
),
),
if (widget.state.activeProject != null &&
(_trashed.isNotEmpty || _showTrash))
ExpansionTile(
title: Text(
context.l10n.agentTrash,
style: AppSidebarTypography.style(
context,
color: AppSidebarColors.of(context).tertiary,
weight: FontWeight.w500,
Consumer(
builder: (context, ref, _) {
ref.watch(
conversationSidebarProvider.select(
(value) => (value.hasError, value.value?.reloadFailed),
),
),
initiallyExpanded: _showTrash,
onExpansionChanged: (value) => setState(() => _showTrash = value),
trailing: _trashed.isEmpty
? null
: TextButton(
onPressed: _emptyTrash,
child: Text(context.l10n.agentEmptyTrash),
),
children: [
ListView.builder(
primary: false,
shrinkWrap: true,
itemCount: _trashed.length,
itemBuilder: (context, index) {
final item = _trashed[index];
return ListTile(
dense: true,
title: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.fontSize,
height: AppSidebarMetrics.lineHeight,
color: AppSidebarColors.of(context).secondary,
),
),
trailing: PopupMenuButton<String>(
tooltip: context.l10n.agentConversationActions,
onSelected: (value) {
if (value == 'restore') {
_restoreConversation(item);
}
if (value == 'delete') _deleteForever(item);
},
itemBuilder: (context) => [
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'restore',
child: Text(context.l10n.agentRestore),
),
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'delete',
child: Text(context.l10n.agentDeleteForever),
),
],
);
return _conversationError == null
? const SizedBox.shrink()
: Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
_conversationError!,
style: Theme.of(context).textTheme.bodySmall,
),
);
},
},
),
Consumer(
builder: (context, ref, _) {
ref.watch(
conversationSidebarProvider.select(
(value) => (value.value?.projectId, value.value?.trashed),
),
],
),
);
return widget.state.activeProject == null ||
(_trashed.isEmpty && !_showTrash)
? const SizedBox.shrink()
: ExpansionTile(
title: Text(
context.l10n.agentTrash,
style: AppSidebarTypography.style(
context,
color: AppSidebarColors.of(context).tertiary,
weight: FontWeight.w500,
),
),
initiallyExpanded: _showTrash,
onExpansionChanged: (value) =>
setState(() => _showTrash = value),
trailing: _trashed.isEmpty
? null
: TextButton(
onPressed: _emptyTrash,
child: Text(context.l10n.agentEmptyTrash),
),
children: [
ListView.builder(
primary: false,
shrinkWrap: true,
itemCount: _trashed.length,
itemBuilder: (context, index) {
final item = _trashed[index];
return ListTile(
dense: true,
title: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.fontSize,
height: AppSidebarMetrics.lineHeight,
color: AppSidebarColors.of(context).secondary,
),
),
trailing: PopupMenuButton<String>(
tooltip: context.l10n.agentConversationActions,
onSelected: (value) {
if (value == 'restore') {
_restoreConversation(item);
}
if (value == 'delete') _deleteForever(item);
},
itemBuilder: (context) => [
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'restore',
child: Text(context.l10n.agentRestore),
),
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'delete',
child: Text(
context.l10n.agentDeleteForever,
),
),
],
),
);
},
),
],
);
},
),
],
),
);
@@ -776,7 +879,28 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
modeHeader,
Expanded(child: projectList),
Expanded(
child: _touch
? projectList
: IndexedStack(
index: widget.resourcesSelected ? 1 : 0,
children: [
TickerMode(
enabled: !widget.resourcesSelected,
child: projectList,
),
TickerMode(
enabled: widget.resourcesSelected,
child: _resourcesVisited
? MediaPanel(
projectId: widget.state.activeProject?.id,
onSelectProject: widget.onSelectProject,
)
: Center(child: Text(context.l10n.projectsNone)),
),
],
),
),
],
),
);
@@ -0,0 +1,60 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
/// Keeps the current content during short switches without delaying completion.
class ProjectSwitchRegion extends StatefulWidget {
const ProjectSwitchRegion({
super.key,
required this.pendingProjectId,
required this.builder,
});
final String? pendingProjectId;
final Widget Function(BuildContext context, bool showDefaults) builder;
@override
State<ProjectSwitchRegion> createState() => _ProjectSwitchRegionState();
}
class _ProjectSwitchRegionState extends State<ProjectSwitchRegion> {
Timer? _timer;
bool _showDefaults = false;
@override
void initState() {
super.initState();
_reset();
}
@override
void didUpdateWidget(covariant ProjectSwitchRegion oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.pendingProjectId != widget.pendingProjectId) _reset();
}
void _reset() {
_timer?.cancel();
_showDefaults = false;
if (widget.pendingProjectId != null) {
_timer = Timer(const Duration(milliseconds: 150), () {
if (mounted) setState(() => _showDefaults = true);
});
}
}
@override
Widget build(BuildContext context) => ExcludeFocus(
excluding: widget.pendingProjectId != null,
child: IgnorePointer(
ignoring: widget.pendingProjectId != null,
child: widget.builder(context, _showDefaults),
),
);
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}
+360 -278
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'dart:async';
@@ -7,9 +8,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../app/adaptive/desktop_workspace_controller.dart';
import '../../app/adaptive/desktop_content_controller.dart';
import '../settings/settings_content.dart';
import '../../app/adaptive/workspace_layout_policy.dart';
import '../../app/shells/phone_workspace_shell.dart';
import '../../app/shells/desktop_workspace_shell.dart';
import '../../app/shells/desktop_window_frame.dart';
import '../../app/shells/tablet_workspace_shell.dart';
import '../../integrations/platform/device_experience.dart';
import '../../integrations/platform/editor_window_chrome.dart';
@@ -30,8 +34,9 @@ import '../../workspace/workspace_session_scope.dart';
import '../assistant/workspace_agent_surface.dart';
import '../editor/background_tasks_button.dart';
import '../editor/editor_page.dart';
import '../settings/settings_dialog.dart';
import '../settings/settings_page.dart';
import 'editor_loading_region.dart';
import 'project_switch_region.dart';
import 'project_sidebar.dart';
import 'widgets/name_dialog.dart';
@@ -103,7 +108,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
if (!created && context.mounted) {
final error = ref.read(projectsProvider).value?.error;
if (error?.requiresProjectLocation == true) {
await showSettingsDialog(context);
await showSettingsPage(context);
}
}
return;
@@ -113,10 +118,13 @@ class _EditingPageState extends ConsumerState<EditingPage> {
.pickDirectory(confirmButtonText: context.l10n.openProject);
if (directory == null || !context.mounted) return;
await ref.read(projectsProvider.notifier).open(directory);
} catch (_) {
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(context.l10n.selectDirectoryFailed)),
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.selectDirectoryFailed),
details: error.toString(),
),
);
}
}
@@ -174,10 +182,11 @@ class _EditingPageState extends ConsumerState<EditingPage> {
ref.watch(workspaceNavigationProvider);
final experience = ref.watch(deviceExperienceProvider);
final desktop = experience == DeviceExperience.desktop;
final contentSelection = ref.watch(desktopContentProvider);
final projects = ref.watch(projectsProvider);
final state = projects.value ?? const ProjectState();
return EditorWindowChrome(
headerHeight: desktop ? AppControlSize.panelHeader : 48,
headerHeight: desktop ? DesktopWindowFrame.headerHeight : 48,
builder: (context, integrated) => Scaffold(
body: SafeArea(
top: !integrated,
@@ -195,120 +204,138 @@ class _EditingPageState extends ConsumerState<EditingPage> {
final navigationHiddenBySpace =
desktop &&
!WorkspaceLayoutPolicy.desktopNavigationFits(
constraints.maxWidth,
constraints.maxWidth -
DesktopWindowFrame.railWidth -
DesktopWindowFrame.contentInset,
);
final navigationCollapsed =
_sidebarCollapsed || navigationHiddenBySpace;
Widget controlSlot(Widget child) {
if (!desktop) {
return SizedBox.square(
dimension: 48,
child: child,
);
}
const buttonSize = AppControlSize.headerButton;
return SizedBox(
width: buttonSize,
height: buttonSize,
child: Center(
child: IconButtonTheme(
data: IconButtonThemeData(
style: Theme.of(context)
.iconButtonTheme
.style
?.copyWith(
fixedSize:
const WidgetStatePropertyAll(
Size.square(buttonSize),
),
minimumSize:
const WidgetStatePropertyAll(
Size.square(buttonSize),
),
maximumSize:
const WidgetStatePropertyAll(
Size.square(buttonSize),
),
padding:
const WidgetStatePropertyAll(
EdgeInsets.zero,
),
tapTargetSize: MaterialTapTargetSize
.shrinkWrap,
),
),
child: SizedBox.square(
dimension: buttonSize,
child: child,
),
),
),
);
}
Widget controls({
bool navigationToggle = true,
}) => HeaderControlRegion(
child: Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny,
children: [
if (navigationToggle)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key(
'project-sidebar-toggle',
),
tooltip: navigationCollapsed
? context.l10n.expandSidebar
: context.l10n.collapseSidebar,
onPressed: () {
if (navigationHiddenBySpace) {
_desktopScaffoldKey.currentState
?.openDrawer();
} else {
_sidebarCollapsed =
!_sidebarCollapsed;
_saveViewState();
}
},
style: sidebarActionButtonStyle(
context,
),
icon: const Icon(
Icons.view_sidebar_outlined,
size: AppIconSize.header,
),
),
),
if (desktop &&
navigationCollapsed &&
navigationToggle)
PopupMenuButton<WorkspaceMode>(
key: const Key('desktop-workspace-mode'),
initialValue: _mode,
onSelected: _setMode,
itemBuilder: (context) => [
for (final mode in WorkspaceMode.values)
PopupMenuItem(
key: ValueKey(
'desktop-mode-${mode.name}',
),
value: mode,
child: Text(
mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
),
child: Padding(
padding: EdgeInsets.only(
left: desktop
? (DesktopWindowFrame.railWidth -
AppControlSize.headerButton) /
2
: 0,
),
child: Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny,
children: [
if (navigationToggle)
controlSlot(
IconButton(
key: const Key(
'project-sidebar-toggle',
),
tooltip: navigationCollapsed
? context.l10n.expandSidebar
: context.l10n.collapseSidebar,
onPressed: () {
if (navigationHiddenBySpace) {
_desktopScaffoldKey.currentState
?.openDrawer();
} else {
_sidebarCollapsed =
!_sidebarCollapsed;
_saveViewState();
}
},
style: sidebarActionButtonStyle(
context,
),
icon: const Icon(
Icons.view_sidebar_outlined,
size: AppIconSize.header,
),
],
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 6,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
),
const Icon(
Icons.keyboard_arrow_down,
size: 16,
),
],
),
),
),
SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('project-settings-button'),
tooltip: context.l10n.settings,
onPressed: () =>
showSettingsDialog(context),
style: sidebarActionButtonStyle(context),
icon: const Icon(
Icons.settings_outlined,
size: AppIconSize.header,
if (!desktop)
SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key(
'project-settings-button',
),
tooltip: context.l10n.settings,
onPressed: () =>
showSettingsPage(context),
style: sidebarActionButtonStyle(
context,
),
icon: const Icon(
Icons.settings_outlined,
size: AppIconSize.header,
),
),
),
),
),
SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: const BackgroundTasksButton(),
),
],
controlSlot(const BackgroundTasksButton()),
],
),
),
);
Widget leading() => Row(
mainAxisSize: MainAxisSize.min,
children: [
if (navigationCollapsed && integrated)
if (!desktop &&
navigationCollapsed &&
integrated)
SizedBox(
width: EditorWindowChrome.leadingWidth,
),
if (navigationCollapsed) controls(),
if (!desktop && navigationCollapsed) controls(),
const SizedBox(width: AppSpacing.compact),
],
);
@@ -330,19 +357,43 @@ class _EditingPageState extends ConsumerState<EditingPage> {
onCreateProject: () =>
_selectProject(context, ref, create: true),
);
void selectSidebar(bool resources) {
ref
.read(desktopContentProvider.notifier)
.select(
resources
? DesktopContent.library
: DesktopContent.workspace,
);
setState(() => _sidebarCollapsed = false);
_saveViewState();
if (navigationHiddenBySpace) {
WidgetsBinding.instance.addPostFrameCallback((
_,
) {
if (mounted) {
_desktopScaffoldKey.currentState
?.openDrawer();
}
});
}
}
Widget navigation({
DesktopWorkspaceGeometry? geometry,
VoidCallback? expandEditor,
bool drawer = false,
}) => ProjectSidebar(
experience: experience,
resourcesSelected:
desktop && contentSelection.resourcesSelected,
key: drawer
? _drawerNavigationKey
: _navigationKey,
agent: desktop && !drawer
? agent
: const SizedBox.shrink(),
navigationOnly: !desktop || drawer,
navigationOnly: true,
onNavigationComplete: desktop && !drawer
? null
: () => Navigator.of(context).maybePop(),
@@ -359,14 +410,15 @@ class _EditingPageState extends ConsumerState<EditingPage> {
state: state,
selectedProjectId:
_selectedProjectId ?? state.activeProject?.id,
integratedTitlebar: integrated,
integratedTitlebar: !desktop && integrated,
externalWindowFrame: desktop && !drawer,
onCreateProject: () =>
_selectProject(context, ref, create: true),
onSelectProject: selectProject,
onRenameProject: (project) =>
_renameProject(context, ref, project),
headerControls: desktop && !drawer
? controls()
? const SizedBox.shrink()
: HeaderControlRegion(
child: Row(
mainAxisSize: MainAxisSize.min,
@@ -386,61 +438,210 @@ class _EditingPageState extends ConsumerState<EditingPage> {
),
),
);
final editor = ProjectLoadingRegion(
loading: _switchingProject,
child:
state.activeProject != null &&
state.timeline != null
? EditorWorkspace(
key: _editorKey,
experience: experience,
projectId: state.activeProject!.id,
timelineId: state.timeline!.id,
projectName: state.activeProject!.name,
showProjectName:
desktop && _mode == WorkspaceMode.cut,
integratedTitlebar: desktop && integrated,
headerLeading:
desktop && _mode == WorkspaceMode.cut
? leading()
: const SizedBox(
width: AppSpacing.compact,
),
)
: EmptyEditor(
state: state,
showProjectName:
desktop && _mode == WorkspaceMode.cut,
headerLeading:
desktop && _mode == WorkspaceMode.cut
? leading()
: const SizedBox(
width: AppSpacing.compact,
),
),
final pendingProject = _switchingProject
? state.recent
.where(
(item) => item.id == _selectedProjectId,
)
.firstOrNull
: null;
final projectLoading =
pendingProject != null &&
pendingProject.id != state.activeProject?.id;
final editor = ProjectSwitchRegion(
pendingProjectId: projectLoading
? pendingProject.id
: null,
builder: (context, showDefaults) {
final displayDefaults =
projectLoading && showDefaults;
final visibleProject = displayDefaults
? pendingProject
: state.activeProject;
return visibleProject != null &&
(displayDefaults ||
state.timeline != null)
? EditorWorkspace(
key: _editorKey,
experience: experience,
projectId: visibleProject.id,
timelineId: displayDefaults
? ''
: state.timeline!.id,
projectName: visibleProject.name,
projectLoading: displayDefaults,
showProjectName:
desktop &&
_mode == WorkspaceMode.cut,
integratedTitlebar: false,
headerLeading: desktop
? const SizedBox.shrink()
: const SizedBox(
width: AppSpacing.compact,
),
)
: EmptyEditor(
desktop: desktop,
state: state,
showProjectName:
desktop &&
_mode == WorkspaceMode.cut,
headerLeading: desktop
? const SizedBox.shrink()
: const SizedBox(
width: AppSpacing.compact,
),
);
},
);
Widget contentSurface(
DesktopContent surface,
Widget child,
) => ExcludeFocus(
excluding:
(contentSelection.surface ==
DesktopContent.settings) !=
(surface == DesktopContent.settings),
child: TickerMode(
enabled:
(contentSelection.surface ==
DesktopContent.settings) ==
(surface == DesktopContent.settings),
child: child,
),
);
Widget desktopContents(
Widget workspace,
) => IndexedStack(
index:
contentSelection.surface ==
DesktopContent.settings
? 1
: 0,
children: [
contentSurface(
DesktopContent.workspace,
workspace,
),
contentSurface(
DesktopContent.settings,
contentSelection.settingsVisited
? SizedBox(
key: const Key(
'desktop-settings-workspace',
),
child: SettingsContent(
cardLayout: true,
initialTab:
contentSelection.settingsTab,
navigationRequest: contentSelection
.settingsRequest,
workspace:
contentSelection.workspace,
),
)
: const SizedBox.shrink(),
),
],
);
return switch (experience) {
DeviceExperience.desktop => DesktopWorkspaceShell(
controller: _desktopSplits,
scaffoldKey: _desktopScaffoldKey,
navigationDrawer: navigation(drawer: true),
mode: _mode,
sidebarCollapsed: navigationCollapsed,
sidebarWidth: _sidebarWidthOverride,
onSidebarCollapsedChanged: (value) {
_sidebarCollapsed = value;
_saveViewState();
DeviceExperience.desktop => DesktopWindowFrame(
integratedTitlebar: integrated,
headerControls: controls(),
librarySelected:
contentSelection.surface ==
DesktopContent.library,
settingsSelected:
contentSelection.surface ==
DesktopContent.settings,
onModeChanged: (mode) {
selectSidebar(false);
_setMode(mode);
},
onSidebarWidthChanged: (value) {
_sidebarWidthOverride = value;
_saveViewState();
},
sidebarBuilder: (geometry, expand) =>
navigation(
geometry: geometry,
expandEditor: expand,
onLibraryPressed: () => selectSidebar(true),
onSettingsPressed: () =>
showSettingsPage(context),
child: desktopContents(
DesktopWorkspaceShell(
controller: _desktopSplits,
scaffoldKey: _desktopScaffoldKey,
navigationDrawer: navigation(drawer: true),
mode: _mode,
sidebarCollapsed: navigationCollapsed,
sidebarWidth: _sidebarWidthOverride,
onSidebarCollapsedChanged: (value) {
_sidebarCollapsed = value;
_saveViewState();
},
onSidebarWidthChanged: (value) {
_sidebarWidthOverride = value;
_saveViewState();
},
sidebarBuilder: (geometry, expand) =>
navigation(
geometry: geometry,
expandEditor: expand,
),
agentBuilder: (geometry, expand) => Column(
children: [
SizedBox(
key: const Key(
'agent-content-header',
),
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.gap,
),
child: Row(
children: [
const Spacer(),
HeaderControlRegion(
child: SizedBox.square(
dimension: AppControlSize
.headerButton,
child: IconButton(
key: const Key(
'agent-fullscreen-button',
),
isSelected:
geometry.editorHidden,
tooltip:
geometry.editorHidden
? context
.l10n
.exitPreviewFullscreen
: context
.l10n
.agentFullscreen,
onPressed:
geometry.editorHidden
? expand
: () => _desktopSplits
.setAgentFullscreen(
true,
),
icon: Icon(
size:
AppIconSize.header,
geometry.editorHidden
? Icons
.fullscreen_exit
: Icons.fullscreen,
),
),
),
),
],
),
),
),
Expanded(child: agent),
],
),
editor: editor,
editor: editor,
),
),
),
DeviceExperience.tablet => TabletWorkspaceShell(
mode: _mode,
@@ -472,10 +673,11 @@ class _EditingPageState extends ConsumerState<EditingPage> {
PositionedDirectional(
top: AppSpacing.compact,
end: AppSpacing.compact,
child: _SonnerErrorToast(
child: ErrorFailureListener(
message: projects.hasError
? const AppFailure(
? AppFailure(
AppErrorCode.loadProjectsFailed,
diagnostic: projects.error.toString(),
)
: state.error,
),
@@ -542,123 +744,3 @@ class _StartupLoadingState extends State<_StartupLoading>
),
);
}
class _SonnerErrorToast extends StatefulWidget {
const _SonnerErrorToast({required this.message});
final AppFailure? message;
@override
State<_SonnerErrorToast> createState() => _SonnerErrorToastState();
}
class _SonnerErrorToastState extends State<_SonnerErrorToast> {
static const _displayDuration = Duration(seconds: 6);
Timer? _timer;
AppFailure? _displayedMessage;
bool _visible = false;
@override
void initState() {
super.initState();
_show(widget.message);
}
@override
void didUpdateWidget(covariant _SonnerErrorToast oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.message != null &&
(oldWidget.message == null || widget.message != oldWidget.message)) {
_show(widget.message);
}
}
void _show(AppFailure? message) {
if (message == null) return;
_timer?.cancel();
_displayedMessage = message;
_visible = true;
_timer = Timer(_displayDuration, _hide);
}
void _hide() {
if (mounted) setState(() => _visible = false);
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final message = _displayedMessage;
if (message == null) return const SizedBox.shrink();
final theme = Theme.of(context);
return IgnorePointer(
ignoring: !_visible,
child: AnimatedSlide(
offset: _visible ? Offset.zero : const Offset(0.08, 0),
duration: const Duration(milliseconds: 180),
curve: Curves.easeOutCubic,
child: AnimatedOpacity(
opacity: _visible ? 1 : 0,
duration: const Duration(milliseconds: 160),
child: Semantics(
liveRegion: true,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 360),
child: DecoratedBox(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
border: Border.all(color: theme.colorScheme.outlineVariant),
borderRadius: BorderRadius.circular(AppRadius.large),
boxShadow: [
BoxShadow(
color: theme.colorScheme.shadow.withValues(alpha: .25),
blurRadius: 16,
offset: const Offset(0, 6),
),
],
),
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: AppSpacing.compact,
top: AppSpacing.small,
bottom: AppSpacing.small,
end: AppSpacing.tiny,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.error_outline,
size: AppIconSize.small,
color: theme.colorScheme.error,
),
const SizedBox(width: AppSpacing.small),
Flexible(
child: Text(
context.l10n.failureMessage(message),
style: theme.textTheme.bodyMedium,
),
),
IconButton(
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: _hide,
icon: const Icon(Icons.close, size: AppIconSize.small),
),
],
),
),
),
),
),
),
),
);
}
}
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/model.dart';
@@ -54,8 +55,8 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
widget.session.setCaption(widget.sequence, command);
return true;
} on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(
error.code == 'staleVersion'
? context.l10n.captionEditChanged
@@ -487,10 +488,8 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
),
);
} on CommandRejected {
ScaffoldMessenger.maybeOf(
context,
)?.showSnackBar(
SnackBar(
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(context.l10n.captionChanged),
),
);
+11 -5
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:math' as math;
import 'package:cutdex_sdk/editor.dart';
@@ -120,9 +122,12 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
void _showError(Object error) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error))));
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
}
@override
@@ -292,9 +297,10 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
localPlayhead,
);
} catch (error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
}
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -86,9 +87,9 @@ class _AgentSettingsPanelState extends ConsumerState<AgentSettingsPanel>
}
}
void _showSaveError() => ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)));
void _showSaveError() => ErrorNotificationHost.of(context).show(
ErrorNotification(content: Text(context.l10n.agentSaveSettingsFailed)),
);
Future<void> _setProviderEnabled(
AgentProviderSettings provider,
+537
View File
@@ -0,0 +1,537 @@
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/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'appearance_settings.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,
}) : assert(initialTab >= 0 && initialTab <= 2);
final int initialTab;
final int navigationRequest;
final bool cardLayout;
final (String, String)? workspace;
@override
ConsumerState<SettingsContent> createState() => _SettingsContentState();
}
class _SettingsContentState extends ConsumerState<SettingsContent> {
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<void> _setMode(AppAppearance appearance) async {
await ref
.read(settingsOperationProvider('appearance').notifier)
.run(
() =>
ref.read(appearanceSettingsProvider.notifier).setMode(appearance),
);
}
Future<void> _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) {
final appearanceSave = ref.watch(settingsOperationProvider('appearance'));
final languageSave = ref.watch(settingsOperationProvider('language'));
final appearance = ref.watch(appearanceSettingsProvider);
final language = ref.watch(languageSettingsProvider);
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,
onChanged: (value) => setState(() => _tab = value),
),
),
),
if (widget.cardLayout)
const SizedBox(
key: Key('settings-card-gap'),
width: WorkspaceLayoutMetrics.desktopSpacing,
)
else
VerticalDivider(
key: const Key('settings-sidebar-divider'),
width: 1,
thickness: 1,
color: Theme.of(context).colorScheme.outlineVariant,
),
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: Icons.settings_outlined,
children: [
AppField(
label: context.l10n.appearance,
orientation: AppFieldOrientation.horizontal,
error:
(appearanceSave.hasError
? context.l10n.saveAppearanceFailed
: null) ??
(appearance.hasError
? context.l10n.loadAppearanceFailed
: null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<AppAppearance>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
AppSettingsMetrics.controlHeight,
value:
appearance.asData?.value ??
AppAppearance.system,
label: context.l10n.theme,
options: [
AppSelectOption(
AppAppearance.system,
context.l10n.system,
),
AppSelectOption(
AppAppearance.penLight,
'Pen · ${context.l10n.light}',
),
AppSelectOption(
AppAppearance.penDark,
'Pen · ${context.l10n.dark}',
),
],
onChanged:
appearanceSave.isLoading ||
appearance.isLoading
? null
: _setMode,
),
),
),
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<AppLanguage>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
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),
),
),
),
],
),
),
),
),
],
),
);
}
}
class _SettingsNavigation extends StatelessWidget {
const _SettingsNavigation({
required this.value,
required this.compact,
required this.onChanged,
});
final int value;
final bool compact;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final entries = [
(context.l10n.general, Icons.settings_outlined),
(context.l10n.agentSettings, Icons.auto_awesome_outlined),
('MCP', Icons.terminal_outlined),
];
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: Text(
context.l10n.settings,
style: theme.textTheme.titleSmall?.copyWith(fontSize: 16),
),
),
for (var index = 0; index < entries.length; index++)
Padding(
padding: const EdgeInsets.only(bottom: 1),
child: Semantics(
selected: value == index,
child: Tooltip(
message: entries[index].$1,
child: TextButton(
key: ValueKey('settings-navigation-$index'),
onPressed: () => onChanged(index),
style: TextButton.styleFrom(
minimumSize: const Size(0, 30),
padding: const EdgeInsets.symmetric(horizontal: 8),
foregroundColor: theme.colorScheme.onSurface,
backgroundColor: value == index
? 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].$2, size: 16),
const SizedBox(width: 8),
],
Expanded(
child: Text(
entries[index].$1,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
),
),
],
),
);
}
}
class _ResourceLocationField extends ConsumerWidget {
const _ResourceLocationField();
Future<void> _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<void> _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))}';
}
}
+17 -505
View File
@@ -1,519 +1,31 @@
import 'package:cutdex/l10n/l10n.dart';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/file_picker.dart';
import '../../workspace/persistence/project_location_directory.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'appearance_settings.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);
Future<void> showSettingsDialog(
BuildContext context, {
(String, String)? workspace,
int initialTab = 0,
}) => showAppDialog<void>(
context: Navigator.of(context, rootNavigator: true).context,
builder: (_) => SettingsDialog(workspace: workspace, initialTab: initialTab),
);
class SettingsDialog extends ConsumerStatefulWidget {
const SettingsDialog({super.key, this.workspace, this.initialTab = 0})
: assert(initialTab >= 0 && initialTab <= 2);
final int initialTab;
import '../../l10n/l10n.dart';
import 'settings_content.dart';
/// Dialog adapter for embedded settings hosts.
class SettingsDialog extends StatelessWidget {
const SettingsDialog({super.key, this.workspace, this.initialTab = 0});
final (String, String)? workspace;
final int initialTab;
@override
ConsumerState<SettingsDialog> createState() => _SettingsDialogState();
}
class _SettingsDialogState extends ConsumerState<SettingsDialog> {
late int _tab = widget.initialTab;
Future<void> _setMode(AppAppearance appearance) async {
await ref
.read(settingsOperationProvider('appearance').notifier)
.run(
() =>
ref.read(appearanceSettingsProvider.notifier).setMode(appearance),
);
}
Future<void> _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: _buildDialog),
);
Widget _buildDialog(BuildContext context) {
final appearanceSave = ref.watch(settingsOperationProvider('appearance'));
final languageSave = ref.watch(settingsOperationProvider('language'));
final appearance = ref.watch(appearanceSettingsProvider);
final language = ref.watch(languageSettingsProvider);
Widget build(BuildContext context) {
final viewport = MediaQuery.sizeOf(context);
return AppDialog(
title: context.l10n.settings,
closeLabel: context.l10n.closeSettings,
width: math.min(1120, math.max(560, viewport.width * .9)),
height: math.min(704, math.max(520, viewport.height * .88)),
contentOnly: true,
scrollContent: false,
child: LayoutBuilder(
builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: constraints.maxWidth < 600 ? 96 : 220,
child: _SettingsNavigation(
value: _tab,
compact: constraints.maxWidth < 600,
onChanged: (value) => setState(() => _tab = value),
),
),
VerticalDivider(
key: const Key('settings-sidebar-divider'),
width: 1,
thickness: 1,
color: Theme.of(context).colorScheme.outlineVariant,
),
Expanded(
child: 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: Icons.settings_outlined,
children: [
AppField(
label: context.l10n.appearance,
orientation: AppFieldOrientation.horizontal,
error:
(appearanceSave.hasError
? context.l10n.saveAppearanceFailed
: null) ??
(appearance.hasError
? context.l10n.loadAppearanceFailed
: null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<AppAppearance>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
AppSettingsMetrics.controlHeight,
value:
appearance.asData?.value ??
AppAppearance.system,
label: context.l10n.theme,
options: [
AppSelectOption(
AppAppearance.system,
context.l10n.system,
),
AppSelectOption(
AppAppearance.penLight,
'Pen · ${context.l10n.light}',
),
AppSelectOption(
AppAppearance.penDark,
'Pen · ${context.l10n.dark}',
),
],
onChanged:
appearanceSave.isLoading ||
appearance.isLoading
? null
: _setMode,
),
),
),
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<AppLanguage>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
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),
),
),
),
],
),
),
),
],
),
return Theme(
data: AppTheme.settingsContentTheme(Theme.of(context)),
child: AppDialog(
title: context.l10n.settings,
closeLabel: context.l10n.closeSettings,
width: math.min(1120, math.max(560, viewport.width * .9)),
height: math.min(704, math.max(520, viewport.height * .88)),
contentOnly: true,
scrollContent: false,
child: SettingsContent(workspace: workspace, initialTab: initialTab),
),
);
}
}
class _SettingsNavigation extends StatelessWidget {
const _SettingsNavigation({
required this.value,
required this.compact,
required this.onChanged,
});
final int value;
final bool compact;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final entries = [
(context.l10n.general, Icons.settings_outlined),
(context.l10n.agentSettings, Icons.auto_awesome_outlined),
('MCP', Icons.terminal_outlined),
];
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: Text(
context.l10n.settings,
style: theme.textTheme.titleSmall?.copyWith(fontSize: 16),
),
),
for (var index = 0; index < entries.length; index++)
Padding(
padding: const EdgeInsets.only(bottom: 1),
child: Semantics(
selected: value == index,
child: Tooltip(
message: entries[index].$1,
child: TextButton(
key: ValueKey('settings-navigation-$index'),
onPressed: () => onChanged(index),
style: TextButton.styleFrom(
minimumSize: const Size(0, 30),
padding: const EdgeInsets.symmetric(horizontal: 8),
foregroundColor: theme.colorScheme.onSurface,
backgroundColor: value == index
? 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].$2, size: 16),
const SizedBox(width: 8),
],
Expanded(
child: Text(
entries[index].$1,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
),
),
],
),
);
}
}
class _ResourceLocationField extends ConsumerWidget {
const _ResourceLocationField();
Future<void> _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<void> _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))}';
}
}
+97
View File
@@ -0,0 +1,97 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../app/shells/desktop_window_frame.dart';
import '../../app/adaptive/desktop_content_controller.dart';
import '../../integrations/platform/device_experience.dart';
import '../../integrations/platform/editor_window_chrome.dart';
import '../../l10n/l10n.dart';
import 'settings_content.dart';
Future<void> showSettingsPage(
BuildContext context, {
(String, String)? workspace,
int? initialTab,
}) {
final container = ProviderScope.containerOf(context, listen: false);
if (container.read(deviceExperienceProvider) == DeviceExperience.desktop) {
container
.read(desktopContentProvider.notifier)
.showSettings(tab: initialTab, workspace: workspace);
return Future<void>.value();
}
return context.push<void>(
'/settings?tab=${initialTab ?? 0}',
extra: workspace,
);
}
/// A pushed route keeps the editor and its session mounted underneath.
class SettingsPage extends ConsumerWidget {
const SettingsPage({super.key, this.workspace, this.initialTab = 0});
final (String, String)? workspace;
final int initialTab;
@override
Widget build(BuildContext context, WidgetRef ref) {
final desktop =
ref.watch(deviceExperienceProvider) == DeviceExperience.desktop;
void back() {
if (context.canPop()) {
context.pop();
} else {
context.go('/');
}
}
final content = SettingsContent(
workspace: workspace,
initialTab: initialTab,
);
if (!desktop) {
return Scaffold(
key: const Key('settings-page'),
appBar: AppBar(
leading: BackButton(
key: const Key('settings-page-back'),
onPressed: back,
),
title: Text(context.l10n.settings),
),
body: content,
);
}
return EditorWindowChrome(
headerHeight: DesktopWindowFrame.headerHeight,
builder: (context, integrated) => Scaffold(
key: const Key('settings-page'),
backgroundColor: Theme.of(context).colorScheme.surfaceContainer,
body: Column(
children: [
SizedBox(
height: DesktopWindowFrame.headerHeight,
child: WindowHeaderPadding(
child: Row(
children: [
if (integrated)
SizedBox(width: EditorWindowChrome.leadingWidth),
HeaderControlRegion(
child: BackButton(
key: const Key('settings-page-back'),
onPressed: back,
),
),
Text(context.l10n.settings),
],
),
),
),
Expanded(child: content),
],
),
),
);
}
}
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'dart:async';
@@ -352,9 +353,12 @@ class TimelineExternalDropTargetState
);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(e))));
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.errorMessage(e)),
details: e.toString(),
),
);
}
} finally {
if (mounted && g == generation) {
+214 -208
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
@@ -7,6 +8,7 @@ import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/projects.dart';
@@ -20,6 +22,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../editor/editor_panel_defaults.dart';
import '../media/transcription_dialog.dart';
import '../media/background_removal_dialog.dart';
import '../projects/widgets/name_dialog.dart';
@@ -28,86 +31,121 @@ import '../../workspace/preview_target.dart';
import 'timeline_asset_drop_target.dart';
import 'timeline_speed_editor.dart';
class EditorTimelinePanel extends ConsumerWidget {
class EditorTimelinePanel extends StatelessWidget {
const EditorTimelinePanel({
super.key,
required this.projectId,
required this.timelineId,
this.pending = false,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context) => Theme(
data: AppTheme.timelinePanelTheme(Theme.of(context)),
child: pending
? const EditorTimelineDefaults()
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_TimelineTabsContent(
projectId: projectId,
timelineId: timelineId,
),
const Divider(height: 1),
Expanded(
child: _TimelineSessionContent(
projectId: projectId,
timelineId: timelineId,
),
),
],
),
);
}
class _TimelineTabsContent extends ConsumerWidget {
const _TimelineTabsContent({
required this.projectId,
required this.timelineId,
});
final String projectId;
final String timelineId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = editorTimelineProvider(projectId, timelineId);
final timeline = ref.watch(provider);
final projectState = ref.watch(projectsProvider).asData?.value;
final timelines = projectState?.activeProject?.id == projectId
? projectState!.timelines
: const <TimelineSummary>[];
return Theme(
data: AppTheme.timelinePanelTheme(Theme.of(context)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_TimelineTabsBar(
projectId: projectId,
timelineId: timelineId,
timelines: timelines,
creating: projectState?.creatingTimeline ?? false,
openingTimelineId: projectState?.openingTimelineId,
),
const Divider(height: 1),
Expanded(
child: timeline.when(
loading: () => const WorkspacePanel(
key: Key('timeline-pending'),
child: SizedBox.expand(),
),
error: (_, _) => WorkspacePanel(
child: Center(
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.openTimelineFailed,
textAlign: TextAlign.center,
),
TextButton(
onPressed: () => ref.invalidate(provider),
child: Text(context.l10n.retry),
),
],
),
),
return _TimelineTabsBar(
projectId: projectId,
timelineId: timelineId,
timelines: timelines,
creating: projectState?.creatingTimeline ?? false,
openingTimelineId: projectState?.openingTimelineId,
);
}
}
class _TimelineSessionContent extends ConsumerWidget {
const _TimelineSessionContent({
required this.projectId,
required this.timelineId,
});
final String projectId;
final String timelineId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = editorTimelineProvider(projectId, timelineId);
final watched = ref.watch(provider);
final cached = watched.isLoading && !watched.hasError
? ref
.read(projectsProvider.notifier)
.cachedTimelineSession(projectId, timelineId)
: null;
final timeline = cached == null ? watched : AsyncData(cached);
return timeline.when(
loading: () => const EditorTimelineDefaults(
key: Key('timeline-pending'),
showTabs: false,
),
error: (_, _) => WorkspacePanel(
child: Center(
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.openTimelineFailed,
textAlign: TextAlign.center,
),
),
data: (session) => Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) {
if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) {
debugPrint(
'CUTDEX_PREVIEW '
'${DateTime.now().millisecondsSinceEpoch} '
'dart pointer-down',
);
}
ref
.read(
previewNavigationProvider(
projectId,
timelineId,
).notifier,
)
.showTimeline();
},
child: _TimelineEditor(session: session, projectId: projectId),
),
TextButton(
onPressed: () => ref.invalidate(provider),
child: Text(context.l10n.retry),
),
],
),
),
],
),
),
data: (session) => Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) {
if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) {
debugPrint(
'CUTDEX_PREVIEW '
'${DateTime.now().millisecondsSinceEpoch} '
'dart pointer-down',
);
}
ref
.read(previewNavigationProvider(projectId, timelineId).notifier)
.showTimeline();
},
child: _TimelineEditor(session: session, projectId: projectId),
),
);
}
@@ -241,8 +279,8 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
Future<void> _createTimeline() async {
if (_operationsBusy) return;
if (widget.timelines.length >= Projects.maxTimelineCount) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(
context.l10n.timelineLimitReached(Projects.maxTimelineCount),
),
@@ -494,60 +532,13 @@ class _TimelineEditor extends StatefulWidget {
class _TimelineEditorState extends State<_TimelineEditor> {
EditorTimelineSession get session => widget.session;
String get projectId => widget.projectId;
late RuntimeTimelineThumbnails _thumbnails;
late RuntimeTimelineWaveforms _waveforms;
RuntimeTimelineThumbnails get _thumbnails => session.thumbnails;
RuntimeTimelineWaveforms get _waveforms => session.waveforms;
@override
void initState() {
super.initState();
_createMediaCaches();
}
@override
void didUpdateWidget(covariant _TimelineEditor oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.session, widget.session)) {
_thumbnails.dispose();
_waveforms.dispose();
_createMediaCaches();
}
}
void _createMediaCaches() {
_thumbnails = RuntimeTimelineThumbnails(
resolveTrackSelection: (ref) => session.mediaBinding(ref)?.videoSelection,
resolveMedia: (ref) {
final binding = session.mediaBinding(ref);
if (session.unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.videoTrackIndex == null ? null : binding!.media;
},
);
_waveforms = RuntimeTimelineWaveforms(
resolveTrackSelection: (ref) => session.mediaBinding(ref)?.audioSelection,
resolveGain: session.waveformGain,
gainChanges: session.audioGainPreview,
resolveMedia: (ref) {
final binding = session.mediaBinding(ref);
if (session.unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.audioTrackIndex == null ? null : binding!.media;
},
);
}
@override
void dispose() {
_thumbnails.dispose();
_waveforms.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => ListenableBuilder(
Widget build(BuildContext context) => ListenableSelector(
listenable: session,
select: () => session.activeSequenceId,
builder: (context, _) => _build(context),
);
@@ -662,8 +653,8 @@ class _TimelineEditorState extends State<_TimelineEditor> {
try {
edit();
} on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(
error.code == 'staleVersion'
? context.l10n.captionChanged
@@ -706,107 +697,121 @@ class _TimelineEditorState extends State<_TimelineEditor> {
);
}
final controller = session.view(sequenceId);
final captionCues = _selectedCaptionCues(controller);
final canSplitCaption = _canSplitCaption(controller, captionCues);
return WorkspacePanel(
headerHeight: 32,
headerPadding: EdgeInsets.zero,
controls: ListenableBuilder(
controls: ListenableSelector(
listenable: Listenable.merge([
controller.contentChanges,
controller.playheadChanges,
session,
]),
builder: (context, _) => SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: IntrinsicWidth(
child: Row(
children: [
Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny,
children: [
_toolbarButton(
tooltip: context.l10n.undo,
onPressed: controller.canUndo
? controller.undo
: null,
icon: Icons.undo,
),
_toolbarButton(
tooltip: context.l10n.redo,
onPressed: controller.canRedo
? controller.redo
: null,
icon: Icons.redo,
),
_toolbarButton(
tooltip: context.l10n.splitAtPlayhead,
onPressed: canSplitCaption
? () => _runCaptionEdit(
context,
() => _splitCaption(
sequenceId,
controller,
captionCues.single,
),
)
: controller.canCutSelection
? controller.cutSelectionAtPlayhead
: null,
icon: Icons.content_cut,
),
_toolbarButton(
key: const ValueKey('timeline-trim-left'),
tooltip: context.l10n.trimLeftTooltip,
onPressed: controller.canCutSelection
? controller.trimLeftAtPlayhead
: null,
icon: Icons.align_horizontal_left,
semanticLabel: context.l10n.trimLeft,
),
_toolbarButton(
key: const ValueKey('timeline-trim-right'),
tooltip: context.l10n.trimRightTooltip,
onPressed: controller.canCutSelection
? controller.trimRightAtPlayhead
: null,
icon: Icons.align_horizontal_right,
semanticLabel: context.l10n.trimRight,
),
_toolbarButton(
key: const ValueKey('timeline-delete-selection'),
tooltip: context.l10n.deleteSelectedClips,
onPressed: () {
if (!controller.canDeleteSelection) return;
controller.deleteSelection();
},
icon: Icons.delete_outline,
),
],
),
const Spacer(),
if (controller.commandRejection != null)
Tooltip(
message: controller.commandRejection!,
child: const Icon(Icons.info_outline),
select: () => (
controller.canUndo,
controller.canRedo,
controller.canCutSelection,
controller.canDeleteSelection,
controller.commandRejection,
_canSplitCaption(controller, _selectedCaptionCues(controller)),
_selectedCaptionCues(controller).singleOrNull,
controller.version.kernelVersion,
),
builder: (context, _) {
final captionCues = _selectedCaptionCues(controller);
final canSplitCaption = _canSplitCaption(controller, captionCues);
return SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: IntrinsicWidth(
child: Row(
children: [
Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny,
children: [
_toolbarButton(
tooltip: context.l10n.undo,
onPressed: controller.canUndo
? controller.undo
: null,
icon: Icons.undo,
),
_toolbarButton(
tooltip: context.l10n.redo,
onPressed: controller.canRedo
? controller.redo
: null,
icon: Icons.redo,
),
_toolbarButton(
tooltip: context.l10n.splitAtPlayhead,
onPressed: canSplitCaption
? () => _runCaptionEdit(
context,
() => _splitCaption(
sequenceId,
controller,
captionCues.single,
),
)
: controller.canCutSelection
? controller.cutSelectionAtPlayhead
: null,
icon: Icons.content_cut,
),
_toolbarButton(
key: const ValueKey('timeline-trim-left'),
tooltip: context.l10n.trimLeftTooltip,
onPressed: controller.canCutSelection
? controller.trimLeftAtPlayhead
: null,
icon: Icons.align_horizontal_left,
semanticLabel: context.l10n.trimLeft,
),
_toolbarButton(
key: const ValueKey('timeline-trim-right'),
tooltip: context.l10n.trimRightTooltip,
onPressed: controller.canCutSelection
? controller.trimRightAtPlayhead
: null,
icon: Icons.align_horizontal_right,
semanticLabel: context.l10n.trimRight,
),
_toolbarButton(
key: const ValueKey(
'timeline-delete-selection',
),
tooltip: context.l10n.deleteSelectedClips,
onPressed: () {
if (!controller.canDeleteSelection) return;
controller.deleteSelection();
},
icon: Icons.delete_outline,
),
],
),
],
const Spacer(),
if (controller.commandRejection != null)
Tooltip(
message: controller.commandRejection!,
child: const Icon(Icons.info_outline),
),
],
),
),
),
),
),
),
),
),
);
},
),
child: ListenableBuilder(
listenable: controller.contentChanges,
@@ -860,9 +865,10 @@ class _TimelineEditorState extends State<_TimelineEditor> {
session.detachAudio(sequenceId, detachTarget);
}
} catch (error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
}
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:math' as math;
import 'package:cutdex_sdk/editor.dart';
@@ -315,9 +317,12 @@ class _ClipSpeedEditorState extends State<_ClipSpeedEditor> {
void _showError(Object error) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error))));
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
}
void _clearDrag() {