Files
pipelines/app/lib/application/pipelines_root.dart
T
alan a49b59a2bc Keep even 16px window margins for top bars on wide windows
On a wide window (both sides at least 600 logical px) every SegmentedBar
keeps the floating tab bar's 16px from the top and the sides, in every
pane and page. A root WindowMargins scope adds the extra 8px to the top
media padding, so Cupertino's fixed reserved bar height, list clearances,
pinned headers and measured overlays all move together; the bar and the
TopGlassStrip read the 16px side inset from the same scope, and sticky
section chevrons keep 16px from the trailing edge. Phones keep 8/12.
2026-11-10 13:09:36 +00:00

394 lines
13 KiB
Dart

import 'dart:async';
import '../core/servers/chat/chat_server_pool.dart';
import '../ui/adaptive/platform.dart';
import '../ui/adaptive/window_margins.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../core/session/server_session.dart';
import '../core/servers/server_catalog.dart';
import '../core/servers/server_catalog_store.dart';
import '../core/servers/server_probe.dart';
import '../core/transport/pipelines_client.dart';
import '../features/onboarding/discovery/server_discovery.dart';
import '../features/onboarding/onboarding_flow.dart';
import '../features/settings/server_connections.dart';
import '../features/settings/saved_servers_section.dart';
import '../features/settings/settings_store.dart';
import '../ui/scale/ui_scale.dart';
import '../ui/theme/app_font_controller.dart';
import '../ui/theme/app_theme.dart';
import 'pipelines_app.dart';
import 'server_endpoint.dart';
/// The phone app's root: onboarding until a server and its password are
/// known, then the app. A saved session the server later refuses brings the
/// password step back; an unreachable server just reconnects in the app.
class PipelinesRoot extends StatefulWidget {
const PipelinesRoot({
super.key,
required this.server,
this.buildDefault = '',
this.signedIn = false,
this.check = ServerSession.check,
this.settingsStore = const SharedPreferencesSettingsStore(),
this.catalogStore = const SharedPreferencesServerCatalogStore(),
this.web = kIsWeb,
this.clientFactory,
this.nativeUpdatesSupported,
this.federatedChats = true,
this.chatPoolFactory,
});
final ServerEndpoint server;
/// The server this build was made for; it pre-fills onboarding.
final String buildDefault;
/// A session is kept on this device.
final bool signedIn;
final ServerCheck check;
final SettingsStore settingsStore;
final ServerCatalogStore catalogStore;
final bool web;
/// Optional capability override for platform hosts and isolated widget tests.
final bool? nativeUpdatesSupported;
final bool federatedChats;
final ChatServerPool Function(ServerConnections)? chatPoolFactory;
final PipelinesClient Function()? clientFactory;
@override
State<PipelinesRoot> createState() => _PipelinesRootState();
}
class _PipelinesRootState extends State<PipelinesRoot> {
late ServerEndpoint _server = widget.server;
late bool _onboarding = widget.server.uri == null || !widget.signedIn;
bool _refused = false;
int _generation = 0;
bool _booting = true;
int _activation = 0;
PipelinesClient? _client;
SavedServer? _activeServer;
ChatServerPool? _chatPool;
void _ensureChatPool() {
if (widget.federatedChats && _chatPool == null) {
_chatPool =
widget.chatPoolFactory?.call(_servers) ??
ChatServerPool(_servers, web: widget.web);
// Settings asks each new machine for its own password through the pool.
_servers.authenticator = _chatPool;
}
}
ServerProbe get _probe => identical(widget.check, ServerSession.check)
? ServerSession.probe
: probeFromCheck(widget.check);
late final ServerConnections _servers = ServerConnections(
store: widget.catalogStore,
onSelected: _selectServer,
replaceRemovedPrimary: !widget.web,
);
@override
void initState() {
super.initState();
_servers.addListener(_onServersChanged);
_loadServers();
}
/// A native host with no saved machine left has nothing to connect to, so
/// it returns to Add server however the last profile went away. Removing a
/// profile that was not the primary never activated anything before, which
/// stranded the app on "Server endpoint not configured".
void _onServersChanged() {
if (widget.web || _booting || _onboarding) return;
if (_servers.catalog.servers.isEmpty) unawaited(_activate(null));
}
Future<void> _loadServers() async {
await _servers.load(legacyEndpoint: widget.server.uri?.toString() ?? '');
if (!mounted) return;
if (widget.web) {
if (widget.server.uri != null) {
_servers.alignBrowserOrigin(widget.server.uri!);
final id = _servers.catalog.active?.id;
if (id != null && Uri.base.queryParameters['newChat'] == '1') {
_servers.restoreNewChatIntent(id);
}
}
_ensureChatPool();
setState(() {
_booting = false;
_onboarding = false;
_client = widget.clientFactory?.call();
});
return;
}
final persisted =
_servers.catalog.active == null || await _servers.persist();
if (!mounted) return;
if (!persisted) {
ServerSession.clearSelection();
setState(() {
_booting = false;
_onboarding = true;
});
return;
}
await _activate(_servers.catalog.active, initial: true);
}
Future<void> _selectServer(SavedServer? server) async {
if (widget.web) {
if (server == null) return;
final endpoint = Uri.parse(server.endpoints.first);
if (endpoint == _server.uri) {
_servers.alignBrowserOrigin(endpoint);
return;
}
final page = endpoint.replace(
scheme: endpoint.scheme == 'wss' ? 'https' : 'http',
path: _servers.newChatServerId == server.id ? '/chat' : '/',
query: _servers.newChatServerId == server.id ? 'newChat=1' : null,
fragment: null,
);
if (!await launchUrl(page, webOnlyWindowName: '_self')) {
if (_server.uri != null) _servers.alignBrowserOrigin(_server.uri!);
throw StateError('Could not open the selected server.');
}
return;
}
if (server != null &&
server.id == _activeServer?.id &&
listEquals(server.endpoints, _activeServer?.endpoints)) {
_activeServer = server;
return;
}
await _activate(server);
}
Future<void> _activate(SavedServer? server, {bool initial = false}) async {
final token = ++_activation;
if (!initial) {
setState(() => _booting = true);
// Dispose the old app/socket before changing the credential namespace.
await WidgetsBinding.instance.endOfFrame;
}
if (!mounted || token != _activation) return;
if (server == null) {
ServerSession.clearSelection();
} else {
await ServerSession.activateServer(
id: server.id,
endpoints: server.endpoints.map(Uri.parse),
migrateLegacy: server.id == 'legacy-server',
);
}
if (!mounted || token != _activation) return;
_activeServer = server;
_ensureChatPool();
setState(() {
_server = ServerEndpoint.resolve(
base: Uri.base,
web: false,
configured: server?.endpoints.first ?? '',
);
_onboarding = widget.federatedChats
? _servers.catalog.servers.isEmpty
: server == null ||
(ServerSession.cookie == null &&
!(initial &&
widget.signedIn &&
server.id == 'legacy-server'));
_refused = false;
_generation++;
_booting = false;
_client = _onboarding ? null : widget.clientFactory?.call();
});
if (!_onboarding && _server.uri != null) {
_verify(_server.uri!);
}
}
/// A kept session the server now refuses asks for the password again.
Future<void> _verify(Uri endpoint) async {
if (widget.federatedChats &&
_chatPool != null &&
_servers.catalog.servers.isNotEmpty) {
return;
}
final token = _activation;
final result = await probeServerAddresses(
[
endpoint,
...?_activeServer?.endpoints
.map(Uri.parse)
.where((uri) => uri != endpoint),
],
probe: _probe,
isCurrent: () => mounted && token == _activation,
);
if (!mounted ||
token != _activation ||
result.state != SessionState.signedOut) {
return;
}
setState(() {
_refused = true;
_onboarding = true;
_server = ServerEndpoint.resolve(
base: Uri.base,
web: false,
configured: result.endpoint.toString(),
);
});
}
void _done(Uri endpoint) {
_ensureChatPool();
_activeServer = _servers.catalog.active;
if (_activeServer != null) unawaited(_chatPool?.retry(_activeServer!.id));
setState(() {
_server = ServerEndpoint.resolve(
base: Uri.base,
web: false,
configured: endpoint.toString(),
);
_onboarding = false;
_refused = false;
_generation++;
_client = widget.clientFactory?.call();
});
}
Future<void> _saveOnboardingServer(
String url, {
String? name,
Iterable<String> aliases = const [],
}) async {
final token = _activation;
SavedServer? target;
for (final server in _servers.catalog.servers) {
if (server.endpoints.contains(url)) target = server;
}
target ??= SavedServer.validated(
id: 'server-${DateTime.now().microsecondsSinceEpoch}',
name: name?.trim().isNotEmpty == true
? name!.trim()
: Uri.parse(url).host,
endpoints: [url, ...aliases],
);
if (!await _servers.save(target, activate: false) ||
!await _servers.select(target.id, activate: false)) {
throw StateError(_servers.error ?? 'Could not save the server.');
}
if (!mounted || token != _activation) {
throw StateError('The selected server changed.');
}
await ServerSession.activateServer(
id: target.id,
endpoints: target.endpoints.map(Uri.parse),
migrateLegacy: target.id == 'legacy-server',
);
await widget.settingsStore.saveServerUrl(url);
}
@override
void dispose() {
_activation++;
_servers.removeListener(_onServersChanged);
_chatPool?.dispose();
_servers.dispose();
super.dispose();
}
bool get _cupertino => prefersCupertino();
@override
Widget build(BuildContext context) {
if (_booting) {
// A temporary App/Navigator would replace the browser's deep-link URL
// before the real Router reads it. Loading must not own navigation.
return MediaQuery.fromView(
view: View.of(context),
child: Directionality(
textDirection: TextDirection.ltr,
child: _cupertino
? const CupertinoTheme(
data: appCupertinoTheme,
child: Center(child: CupertinoActivityIndicator()),
)
: Theme(
data: appLightTheme(),
child: const Center(child: CircularProgressIndicator()),
),
),
);
}
if (!_onboarding) {
return PipelinesApp(
androidSupported: widget.nativeUpdatesSupported,
chatPool: _chatPool,
key: ValueKey(_generation),
server: _server,
client: _client,
knownServer: true,
serverAddresses: widget.web
? null
: _servers.catalog.active?.endpoints.map(Uri.parse).toList(),
serverId: _servers.catalog.active?.id,
servers: _servers,
legacyPendingEndpoints: [?_servers.catalog.active?.legacyEndpoint],
resetRoute: !widget.web && _generation > 1,
);
}
final flow = OnboardingFlow(
initialServer: _server.uri?.toString() ?? widget.buildDefault,
startAtPassword: _refused,
probe: _probe,
saveServer: _saveOnboardingServer,
saveServerProfile: (url, name) => _saveOnboardingServer(url, name: name),
saveMachine: (endpoints, name) => _saveOnboardingServer(
endpoints.first,
name: name,
aliases: endpoints.skip(1),
),
onDone: _done,
savedServers: SavedServersSection(connections: _servers),
discovery: platformServerDiscovery(web: widget.web),
serverAddresses:
_servers.catalog.active?.endpoints.map(Uri.parse).toList() ??
const [],
);
final fonts = AppFontController.instance;
return ListenableBuilder(
listenable: fonts,
builder: (context, _) => _cupertino
? CupertinoApp(
title: 'Pipelines',
builder: (context, child) => UiScaleHost(
child: WindowMargins(child: child ?? const SizedBox.shrink()),
),
theme: appCupertinoThemeWith(fontFamily: fonts.family),
debugShowCheckedModeBanner: false,
home: flow,
)
: MaterialApp(
title: 'Pipelines',
builder: (context, child) => UiScaleHost(
child: WindowMargins(child: child ?? const SizedBox.shrink()),
),
theme: appLightTheme(fontFamily: fonts.family),
darkTheme: appDarkTheme(fontFamily: fonts.family),
debugShowCheckedModeBanner: false,
home: flow,
),
);
}
}