mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-18 22:33:42 +00:00
feat: new ui (#1455)
This commit is contained in:
742 files changed
+59951
-5934
No files matched your search
@@ -0,0 +1,170 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../api/api.dart' as api;
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../api/model/create_task_batch.dart';
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../api/model/extension.dart';
|
||||
import '../../api/model/install_extension.dart';
|
||||
import '../../api/model/resolve_result.dart';
|
||||
import '../../api/model/resolve_task.dart';
|
||||
import '../../api/model/switch_extension.dart';
|
||||
import '../../api/model/task.dart';
|
||||
import '../../api/model/update_check_extension_resp.dart';
|
||||
import '../../api/model/update_extension_settings.dart';
|
||||
import '../../database/database.dart';
|
||||
import '../window/app_window_appearance.dart';
|
||||
import 'capability_rpc.dart';
|
||||
import 'gopeed_capability.dart';
|
||||
import 'storage_capability.dart';
|
||||
|
||||
class AppCapabilities {
|
||||
AppCapabilities(CapabilityInvoker invoker) : gopeed = GopeedService(invoker), storage = AppStorageService(invoker);
|
||||
|
||||
final GopeedService gopeed;
|
||||
final AppStorageService storage;
|
||||
}
|
||||
|
||||
class LocalAppCapabilities {
|
||||
LocalAppCapabilities._() : codecs = createAppCapabilityCodecs() {
|
||||
registry = CapabilityRegistry(codecs);
|
||||
_bindGopeed(registry);
|
||||
_bindStorage(registry);
|
||||
capabilities = AppCapabilities(LocalCapabilityInvoker(registry));
|
||||
}
|
||||
|
||||
static final instance = LocalAppCapabilities._();
|
||||
|
||||
final RpcCodecRegistry codecs;
|
||||
late CapabilityRegistry registry;
|
||||
late AppCapabilities capabilities;
|
||||
}
|
||||
|
||||
final appCapabilitiesProvider = Provider<AppCapabilities>((ref) => LocalAppCapabilities.instance.capabilities);
|
||||
final gopeedServiceProvider = Provider<GopeedService>((ref) => ref.watch(appCapabilitiesProvider).gopeed);
|
||||
final appStorageServiceProvider = Provider<AppStorageService>((ref) => ref.watch(appCapabilitiesProvider).storage);
|
||||
|
||||
RpcCodecRegistry createAppCapabilityCodecs() {
|
||||
final codecs = RpcCodecRegistry();
|
||||
codecs
|
||||
..register<AppWindowAppearance>((json) => AppWindowAppearance.fromJson(json! as Map<String, dynamic>))
|
||||
..register<ResolveTask>((json) => ResolveTask.fromJson(json! as Map<String, dynamic>))
|
||||
..register<ResolveResult>((json) => ResolveResult.fromJson(json! as Map<String, dynamic>))
|
||||
..register<CreateTask>((json) => CreateTask.fromJson(json! as Map<String, dynamic>))
|
||||
..register<CreateTaskBatch>((json) => CreateTaskBatch.fromJson(json! as Map<String, dynamic>))
|
||||
..register<DownloaderConfig>((json) => DownloaderConfig.fromJson(json! as Map<String, dynamic>))
|
||||
..register<TaskRuntimeStatus>((json) => TaskRuntimeStatus.fromJson(json! as Map<String, dynamic>))
|
||||
..register<List<Task>>(
|
||||
(json) =>
|
||||
(json! as List<dynamic>).map((item) => Task.fromJson(item as Map<String, dynamic>)).toList(growable: false),
|
||||
)
|
||||
..register<InstallExtension>((json) => InstallExtension.fromJson(json! as Map<String, dynamic>))
|
||||
..register<UpdateExtensionSettings>((json) => UpdateExtensionSettings.fromJson(json! as Map<String, dynamic>))
|
||||
..register<SwitchExtension>((json) => SwitchExtension.fromJson(json! as Map<String, dynamic>))
|
||||
..register<List<Extension>>(
|
||||
(json) => (json! as List<dynamic>)
|
||||
.map((item) => Extension.fromJson(item as Map<String, dynamic>))
|
||||
.toList(growable: false),
|
||||
)
|
||||
..register<UpdateCheckExtensionResp>((json) => UpdateCheckExtensionResp.fromJson(json! as Map<String, dynamic>));
|
||||
return codecs;
|
||||
}
|
||||
|
||||
void _bindGopeed(CapabilityRegistry registry) {
|
||||
registry
|
||||
..bind(GopeedMethods.resolve, api.resolve)
|
||||
..bind(GopeedMethods.createTask, api.createTask)
|
||||
..bind(GopeedMethods.createTaskBatch, api.createTaskBatch)
|
||||
..bind(GopeedMethods.patchTask, (params) async {
|
||||
await api.patchTask(params['id'] as String, ResolveTask.fromJson(params['request'] as Map<String, dynamic>));
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(
|
||||
GopeedMethods.getTasks,
|
||||
(statuses) => api.getTasks(statuses.map((name) => Status.values.byName(name)).toList(growable: false)),
|
||||
)
|
||||
..bind(GopeedMethods.getTaskStatus, api.getTaskStatus)
|
||||
..bind(GopeedMethods.getTaskStats, api.getTaskStats)
|
||||
..bind(GopeedMethods.pauseTask, (id) async {
|
||||
await api.pauseTask(id);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.continueTask, (id) async {
|
||||
await api.continueTask(id);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.pauseTasks, (params) async {
|
||||
await api.pauseAllTasks(_optionalStringList(params['ids']));
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.continueTasks, (params) async {
|
||||
await api.continueAllTasks(_optionalStringList(params['ids']));
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.deleteTask, (params) async {
|
||||
await api.deleteTask(params['id'] as String, params['force'] as bool? ?? false);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.deleteTasks, (params) async {
|
||||
await api.deleteTasks(_optionalStringList(params['ids']), params['force'] as bool? ?? false);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.getConfig, (_) => api.getConfig())
|
||||
..bind(GopeedMethods.putConfig, (config) async {
|
||||
await api.putConfig(config);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.installExtension, api.installExtension)
|
||||
..bind(GopeedMethods.getExtensions, (_) => api.getExtensions())
|
||||
..bind(GopeedMethods.updateExtensionSettings, (params) async {
|
||||
await api.updateExtensionSettings(
|
||||
params['identity'] as String,
|
||||
UpdateExtensionSettings.fromJson(params['request'] as Map<String, dynamic>),
|
||||
);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.switchExtension, (params) async {
|
||||
await api.switchExtension(
|
||||
params['identity'] as String,
|
||||
SwitchExtension.fromJson(params['request'] as Map<String, dynamic>),
|
||||
);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.deleteExtension, (identity) async {
|
||||
await api.deleteExtension(identity);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.checkExtensionUpdate, api.upgradeCheckExtension)
|
||||
..bind(GopeedMethods.updateExtension, (identity) async {
|
||||
await api.updateExtension(identity);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(GopeedMethods.testWebhook, (url) async {
|
||||
await api.testWebhook(url);
|
||||
return const RpcUnit();
|
||||
});
|
||||
}
|
||||
|
||||
void _bindStorage(CapabilityRegistry registry) {
|
||||
registry
|
||||
..bind(StorageMethods.getCreateHistory, (_) async => Database.instance.getCreateHistory() ?? const <String>[])
|
||||
..bind(StorageMethods.saveCreateHistory, (urls) async {
|
||||
for (final url in urls) {
|
||||
Database.instance.saveCreateHistory(url);
|
||||
}
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(StorageMethods.removeCreateHistory, (url) async {
|
||||
Database.instance.removeCreateHistory(url);
|
||||
return const RpcUnit();
|
||||
})
|
||||
..bind(StorageMethods.clearCreateHistory, (_) async {
|
||||
Database.instance.clearCreateHistory();
|
||||
return const RpcUnit();
|
||||
});
|
||||
}
|
||||
|
||||
List<String>? _optionalStringList(Object? value) {
|
||||
if (value == null) return null;
|
||||
return (value as List<dynamic>).map((item) => item.toString()).toList(growable: false);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import 'dart:async';
|
||||
|
||||
typedef RpcDecoder<T> = T Function(Object? json);
|
||||
|
||||
class RpcUnit {
|
||||
const RpcUnit();
|
||||
}
|
||||
|
||||
class RpcMethod<P, R> {
|
||||
const RpcMethod(this.name);
|
||||
|
||||
final String name;
|
||||
}
|
||||
|
||||
class CapabilityException implements Exception {
|
||||
const CapabilityException(this.code, this.message, [this.details]);
|
||||
|
||||
final String code;
|
||||
final String message;
|
||||
final Object? details;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
class RpcCodecRegistry {
|
||||
final Map<Type, RpcDecoder<Object?>> _decoders = {};
|
||||
|
||||
void register<T>(RpcDecoder<T> decoder) {
|
||||
_decoders[T] = (json) => decoder(json);
|
||||
}
|
||||
|
||||
Object? encode(Object? value) {
|
||||
if (value == null || value is String || value is num || value is bool) {
|
||||
return value;
|
||||
}
|
||||
if (value is RpcUnit) {
|
||||
return const <String, Object?>{};
|
||||
}
|
||||
if (value is Enum) {
|
||||
return value.name;
|
||||
}
|
||||
if (value is Iterable) {
|
||||
return value.map(encode).toList(growable: false);
|
||||
}
|
||||
if (value is Map) {
|
||||
return {for (final entry in value.entries) entry.key.toString(): encode(entry.value)};
|
||||
}
|
||||
try {
|
||||
return encode((value as dynamic).toJson());
|
||||
} catch (_) {
|
||||
throw CapabilityException('encode_error', 'No RPC encoder registered for ${value.runtimeType}');
|
||||
}
|
||||
}
|
||||
|
||||
T decode<T>(Object? value) {
|
||||
final normalized = _normalize(value);
|
||||
if (T == RpcUnit) {
|
||||
return const RpcUnit() as T;
|
||||
}
|
||||
if (normalized == null) {
|
||||
return null as T;
|
||||
}
|
||||
if (T == List<String>) {
|
||||
return (normalized as List<dynamic>).map((item) => item.toString()).toList(growable: false) as T;
|
||||
}
|
||||
if (normalized is T) {
|
||||
return normalized as T;
|
||||
}
|
||||
final decoder = _decoders[T];
|
||||
if (decoder == null) {
|
||||
throw CapabilityException('decode_error', 'No RPC decoder registered for $T');
|
||||
}
|
||||
return decoder(normalized) as T;
|
||||
}
|
||||
|
||||
Object? _normalize(Object? value) {
|
||||
if (value is Map) {
|
||||
return {for (final entry in value.entries) entry.key.toString(): _normalize(entry.value)};
|
||||
}
|
||||
if (value is List) {
|
||||
return value.map(_normalize).toList(growable: false);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
abstract interface class CapabilityInvoker {
|
||||
Future<R> invoke<P, R>(RpcMethod<P, R> method, P params);
|
||||
}
|
||||
|
||||
typedef _RawCapabilityHandler = Future<Object?> Function(Object? payload);
|
||||
|
||||
class CapabilityRegistry {
|
||||
CapabilityRegistry(this.codecs);
|
||||
|
||||
final RpcCodecRegistry codecs;
|
||||
final Map<String, _RawCapabilityHandler> _handlers = {};
|
||||
final Map<String, Object> _localHandlers = {};
|
||||
|
||||
void bind<P, R>(RpcMethod<P, R> method, FutureOr<R> Function(P params) handler) {
|
||||
if (_handlers.containsKey(method.name)) {
|
||||
throw StateError('Capability already registered: ${method.name}');
|
||||
}
|
||||
_localHandlers[method.name] = handler;
|
||||
_handlers[method.name] = (payload) async {
|
||||
final params = codecs.decode<P>(payload);
|
||||
return codecs.encode(await handler(params));
|
||||
};
|
||||
}
|
||||
|
||||
Future<Object?> invoke(String operation, Object? payload) async {
|
||||
final handler = _handlers[operation];
|
||||
if (handler == null) {
|
||||
throw CapabilityException('method_not_found', 'Capability not found: $operation');
|
||||
}
|
||||
return handler(payload);
|
||||
}
|
||||
|
||||
Future<R> invokeLocal<P, R>(RpcMethod<P, R> method, P params) async {
|
||||
final handler = _localHandlers[method.name];
|
||||
if (handler == null) {
|
||||
throw CapabilityException('method_not_found', 'Capability not found: ${method.name}');
|
||||
}
|
||||
return await (handler as FutureOr<R> Function(P))(params);
|
||||
}
|
||||
}
|
||||
|
||||
class LocalCapabilityInvoker implements CapabilityInvoker {
|
||||
const LocalCapabilityInvoker(this.registry);
|
||||
|
||||
final CapabilityRegistry registry;
|
||||
|
||||
@override
|
||||
Future<R> invoke<P, R>(RpcMethod<P, R> method, P params) async {
|
||||
return registry.invokeLocal(method, params);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../api/model/create_task_batch.dart';
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../api/model/extension.dart';
|
||||
import '../../api/model/install_extension.dart';
|
||||
import '../../api/model/resolve_result.dart';
|
||||
import '../../api/model/resolve_task.dart';
|
||||
import '../../api/model/switch_extension.dart';
|
||||
import '../../api/model/task.dart';
|
||||
import '../../api/model/update_check_extension_resp.dart';
|
||||
import '../../api/model/update_extension_settings.dart';
|
||||
import 'capability_rpc.dart';
|
||||
|
||||
abstract final class GopeedMethods {
|
||||
static const resolve = RpcMethod<ResolveTask, ResolveResult>('gopeed.resolve');
|
||||
static const createTask = RpcMethod<CreateTask, String>('gopeed.task.create');
|
||||
static const createTaskBatch = RpcMethod<CreateTaskBatch, List<String>>('gopeed.task.createBatch');
|
||||
static const patchTask = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.task.patch');
|
||||
static const getTasks = RpcMethod<List<String>, List<Task>>('gopeed.task.list');
|
||||
static const getTaskStatus = RpcMethod<String, TaskRuntimeStatus>('gopeed.task.status');
|
||||
static const getTaskStats = RpcMethod<String, Map<String, dynamic>>('gopeed.task.stats');
|
||||
static const pauseTask = RpcMethod<String, RpcUnit>('gopeed.task.pause');
|
||||
static const continueTask = RpcMethod<String, RpcUnit>('gopeed.task.continue');
|
||||
static const pauseTasks = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.task.pauseBatch');
|
||||
static const continueTasks = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.task.continueBatch');
|
||||
static const deleteTask = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.task.delete');
|
||||
static const deleteTasks = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.task.deleteBatch');
|
||||
static const getConfig = RpcMethod<RpcUnit, DownloaderConfig>('gopeed.config.get');
|
||||
static const putConfig = RpcMethod<DownloaderConfig, RpcUnit>('gopeed.config.put');
|
||||
static const installExtension = RpcMethod<InstallExtension, String>('gopeed.extension.install');
|
||||
static const getExtensions = RpcMethod<RpcUnit, List<Extension>>('gopeed.extension.list');
|
||||
static const updateExtensionSettings = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.extension.updateSettings');
|
||||
static const switchExtension = RpcMethod<Map<String, dynamic>, RpcUnit>('gopeed.extension.switch');
|
||||
static const deleteExtension = RpcMethod<String, RpcUnit>('gopeed.extension.delete');
|
||||
static const checkExtensionUpdate = RpcMethod<String, UpdateCheckExtensionResp>('gopeed.extension.checkUpdate');
|
||||
static const updateExtension = RpcMethod<String, RpcUnit>('gopeed.extension.update');
|
||||
static const testWebhook = RpcMethod<String, RpcUnit>('gopeed.webhook.test');
|
||||
}
|
||||
|
||||
class GopeedService {
|
||||
const GopeedService(this._invoker);
|
||||
|
||||
final CapabilityInvoker _invoker;
|
||||
|
||||
Future<ResolveResult> resolve(ResolveTask request) => _invoker.invoke(GopeedMethods.resolve, request);
|
||||
|
||||
Future<String> createTask(CreateTask request) => _invoker.invoke(GopeedMethods.createTask, request);
|
||||
|
||||
Future<List<String>> createTaskBatch(CreateTaskBatch request) =>
|
||||
_invoker.invoke(GopeedMethods.createTaskBatch, request);
|
||||
|
||||
Future<void> patchTask(String id, ResolveTask request) async {
|
||||
await _invoker.invoke(GopeedMethods.patchTask, {'id': id, 'request': request.toJson()});
|
||||
}
|
||||
|
||||
Future<List<Task>> getTasks(List<Status> statuses) =>
|
||||
_invoker.invoke(GopeedMethods.getTasks, statuses.map((status) => status.name).toList(growable: false));
|
||||
|
||||
Future<TaskRuntimeStatus> getTaskStatus(String id) => _invoker.invoke(GopeedMethods.getTaskStatus, id);
|
||||
|
||||
Future<Map<String, dynamic>> getTaskStats(String id) => _invoker.invoke(GopeedMethods.getTaskStats, id);
|
||||
|
||||
Future<void> pauseTask(String id) async => _invoker.invoke(GopeedMethods.pauseTask, id);
|
||||
|
||||
Future<void> continueTask(String id) async => _invoker.invoke(GopeedMethods.continueTask, id);
|
||||
|
||||
Future<void> pauseAllTasks(List<String>? ids) async {
|
||||
await _invoker.invoke(GopeedMethods.pauseTasks, {'ids': ids});
|
||||
}
|
||||
|
||||
Future<void> continueAllTasks(List<String>? ids) async {
|
||||
await _invoker.invoke(GopeedMethods.continueTasks, {'ids': ids});
|
||||
}
|
||||
|
||||
Future<void> deleteTask(String id, bool force) async {
|
||||
await _invoker.invoke(GopeedMethods.deleteTask, {'id': id, 'force': force});
|
||||
}
|
||||
|
||||
Future<void> deleteTasks(List<String>? ids, bool force) async {
|
||||
await _invoker.invoke(GopeedMethods.deleteTasks, {'ids': ids, 'force': force});
|
||||
}
|
||||
|
||||
Future<DownloaderConfig> getConfig() => _invoker.invoke(GopeedMethods.getConfig, const RpcUnit());
|
||||
|
||||
Future<void> putConfig(DownloaderConfig config) async => _invoker.invoke(GopeedMethods.putConfig, config);
|
||||
|
||||
Future<String> installExtension(InstallExtension request) => _invoker.invoke(GopeedMethods.installExtension, request);
|
||||
|
||||
Future<List<Extension>> getExtensions() => _invoker.invoke(GopeedMethods.getExtensions, const RpcUnit());
|
||||
|
||||
Future<void> updateExtensionSettings(String identity, UpdateExtensionSettings request) async {
|
||||
await _invoker.invoke(GopeedMethods.updateExtensionSettings, {'identity': identity, 'request': request.toJson()});
|
||||
}
|
||||
|
||||
Future<void> switchExtension(String identity, SwitchExtension request) async {
|
||||
await _invoker.invoke(GopeedMethods.switchExtension, {'identity': identity, 'request': request.toJson()});
|
||||
}
|
||||
|
||||
Future<void> deleteExtension(String identity) async => _invoker.invoke(GopeedMethods.deleteExtension, identity);
|
||||
|
||||
Future<UpdateCheckExtensionResp> upgradeCheckExtension(String identity) =>
|
||||
_invoker.invoke(GopeedMethods.checkExtensionUpdate, identity);
|
||||
|
||||
Future<void> updateExtension(String identity) async => _invoker.invoke(GopeedMethods.updateExtension, identity);
|
||||
|
||||
Future<void> testWebhook(String url) async => _invoker.invoke(GopeedMethods.testWebhook, url);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'capability_rpc.dart';
|
||||
|
||||
abstract final class StorageMethods {
|
||||
static const getCreateHistory = RpcMethod<RpcUnit, List<String>>('storage.createHistory.get');
|
||||
static const saveCreateHistory = RpcMethod<List<String>, RpcUnit>('storage.createHistory.save');
|
||||
static const removeCreateHistory = RpcMethod<String, RpcUnit>('storage.createHistory.remove');
|
||||
static const clearCreateHistory = RpcMethod<RpcUnit, RpcUnit>('storage.createHistory.clear');
|
||||
}
|
||||
|
||||
class AppStorageService {
|
||||
const AppStorageService(this._invoker);
|
||||
|
||||
final CapabilityInvoker _invoker;
|
||||
|
||||
Future<List<String>> getCreateHistory() => _invoker.invoke(StorageMethods.getCreateHistory, const RpcUnit());
|
||||
|
||||
Future<void> saveCreateHistory(List<String> urls) async {
|
||||
if (urls.isEmpty) return;
|
||||
await _invoker.invoke(StorageMethods.saveCreateHistory, urls);
|
||||
}
|
||||
|
||||
Future<void> removeCreateHistory(String url) async {
|
||||
await _invoker.invoke(StorageMethods.removeCreateHistory, url);
|
||||
}
|
||||
|
||||
Future<void> clearCreateHistory() async {
|
||||
await _invoker.invoke(StorageMethods.clearCreateHistory, const RpcUnit());
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,7 @@ class LibgopeedChannel implements LibgopeedInterface {
|
||||
|
||||
@override
|
||||
Future<int> start(StartConfig cfg) async {
|
||||
final port = await _channel.invokeMethod('start', {
|
||||
'cfg': jsonEncode(cfg),
|
||||
});
|
||||
final port = await _channel.invokeMethod('start', {'cfg': jsonEncode(cfg)});
|
||||
return port as int;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,7 @@ class WebViewRpcConfig {
|
||||
|
||||
WebViewRpcConfig();
|
||||
|
||||
factory WebViewRpcConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$WebViewRpcConfigFromJson(json);
|
||||
factory WebViewRpcConfig.fromJson(Map<String, dynamic> json) => _$WebViewRpcConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$WebViewRpcConfigToJson(this);
|
||||
}
|
||||
@@ -28,8 +27,7 @@ class StartConfig {
|
||||
|
||||
StartConfig();
|
||||
|
||||
factory StartConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$StartConfigFromJson(json);
|
||||
factory StartConfig.fromJson(Map<String, dynamic> json) => _$StartConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$StartConfigToJson(this);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ Map<String, dynamic> _$WebViewRpcConfigToJson(WebViewRpcConfig instance) =>
|
||||
<String, dynamic>{
|
||||
'network': instance.network,
|
||||
'address': instance.address,
|
||||
'token': instance.token,
|
||||
'token': ?instance.token,
|
||||
};
|
||||
|
||||
StartConfig _$StartConfigFromJson(Map<String, dynamic> json) => StartConfig()
|
||||
@@ -29,7 +29,8 @@ StartConfig _$StartConfigFromJson(Map<String, dynamic> json) => StartConfig()
|
||||
..webViewRpcConfig = json['webViewRpcConfig'] == null
|
||||
? null
|
||||
: WebViewRpcConfig.fromJson(
|
||||
json['webViewRpcConfig'] as Map<String, dynamic>);
|
||||
json['webViewRpcConfig'] as Map<String, dynamic>,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$StartConfigToJson(StartConfig instance) =>
|
||||
<String, dynamic>{
|
||||
@@ -39,5 +40,5 @@ Map<String, dynamic> _$StartConfigToJson(StartConfig instance) =>
|
||||
'storageDir': instance.storageDir,
|
||||
'refreshInterval': instance.refreshInterval,
|
||||
'apiToken': instance.apiToken,
|
||||
'webViewRpcConfig': instance.webViewRpcConfig,
|
||||
'webViewRpcConfig': ?instance.webViewRpcConfig,
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import '../../database/database.dart';
|
||||
import '../../util/util.dart';
|
||||
|
||||
class AppInitializer {
|
||||
static Future<void>? _storageInitialization;
|
||||
static Future<void>? _databaseInitialization;
|
||||
|
||||
static Future<void> ensureStorageInitialized() {
|
||||
return _storageInitialization ??= Util.initStorageDir();
|
||||
}
|
||||
|
||||
static Future<void> ensureDatabaseInitialized() {
|
||||
return _databaseInitialization ??= _initializeDatabase();
|
||||
}
|
||||
|
||||
static Future<void> _initializeDatabase() async {
|
||||
await ensureStorageInitialized();
|
||||
await Database.instance.init();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
class AppStartupOptions {
|
||||
const AppStartupOptions({required this.hidden});
|
||||
|
||||
factory AppStartupOptions.fromArgs(List<String> args) {
|
||||
return AppStartupOptions(
|
||||
hidden: args.contains('--hidden') || args.map(Uri.tryParse).whereType<Uri>().any(isSilentGopeedWakeUri),
|
||||
);
|
||||
}
|
||||
|
||||
final bool hidden;
|
||||
|
||||
AppStartupOptions withInitialUri(Uri? uri) {
|
||||
return AppStartupOptions(hidden: hidden || (uri != null && isSilentGopeedWakeUri(uri)));
|
||||
}
|
||||
}
|
||||
|
||||
bool isSilentGopeedWakeUri(Uri uri) {
|
||||
if (uri.scheme.toLowerCase() != 'gopeed' || uri.queryParameters['hidden'] != 'true') {
|
||||
return false;
|
||||
}
|
||||
return uri.path.isEmpty || uri.path == '/';
|
||||
}
|
||||
@@ -9,9 +9,7 @@ LibgopeedBoot create() => LibgopeedBootBrowser();
|
||||
class LibgopeedBootBrowser implements LibgopeedBoot {
|
||||
// do nothing
|
||||
@override
|
||||
Future<int> start(StartConfig cfg) async {
|
||||
return 0;
|
||||
}
|
||||
Future<int> start(StartConfig cfg) async => 0;
|
||||
|
||||
@override
|
||||
Future<void> stop() async {}
|
||||
|
||||
@@ -38,8 +38,7 @@ class LibgopeedBootNative implements LibgopeedBoot {
|
||||
cfg.storage = 'bolt';
|
||||
cfg.storageDir = Util.getStorageDir();
|
||||
cfg.refreshInterval = 0;
|
||||
var port = await _libgopeed.start(cfg);
|
||||
return port;
|
||||
return _libgopeed.start(cfg);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
class AppException implements Exception {
|
||||
const AppException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => 'AppException: $message';
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,29 @@
|
||||
// Generated by gopeed-file-category-icons. Do not edit by hand.
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
abstract final class GopeedIcons {
|
||||
static const String _fontFamily = 'GopeedIcons';
|
||||
static const IconData protocolBt = IconData(0xe900, fontFamily: _fontFamily);
|
||||
static const IconData protocolEd2k = IconData(0xe901, fontFamily: _fontFamily);
|
||||
static const IconData folder = IconData(0xe902, fontFamily: _fontFamily);
|
||||
static const IconData folderBt = IconData(0xe903, fontFamily: _fontFamily);
|
||||
static const IconData file = IconData(0xe904, fontFamily: _fontFamily);
|
||||
static const IconData fileInstaller = IconData(0xe905, fontFamily: _fontFamily);
|
||||
static const IconData fileAndroid = IconData(0xe906, fontFamily: _fontFamily);
|
||||
static const IconData fileIos = IconData(0xe907, fontFamily: _fontFamily);
|
||||
static const IconData fileDiskImage = IconData(0xe908, fontFamily: _fontFamily);
|
||||
static const IconData fileWeb = IconData(0xe909, fontFamily: _fontFamily);
|
||||
static const IconData fileText = IconData(0xe90a, fontFamily: _fontFamily);
|
||||
static const IconData filePdf = IconData(0xe90b, fontFamily: _fontFamily);
|
||||
static const IconData fileDocument = IconData(0xe90c, fontFamily: _fontFamily);
|
||||
static const IconData fileSpreadsheet = IconData(0xe90d, fontFamily: _fontFamily);
|
||||
static const IconData filePresentation = IconData(0xe90e, fontFamily: _fontFamily);
|
||||
static const IconData fileArchive = IconData(0xe90f, fontFamily: _fontFamily);
|
||||
static const IconData fileImage = IconData(0xe910, fontFamily: _fontFamily);
|
||||
static const IconData fileAudio = IconData(0xe911, fontFamily: _fontFamily);
|
||||
static const IconData fileVideo = IconData(0xe912, fontFamily: _fontFamily);
|
||||
static const IconData fileCode = IconData(0xe913, fontFamily: _fontFamily);
|
||||
static const IconData fileEbook = IconData(0xe914, fontFamily: _fontFamily);
|
||||
static const IconData fileFont = IconData(0xe915, fontFamily: _fontFamily);
|
||||
static const IconData fileDatabase = IconData(0xe916, fontFamily: _fontFamily);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
class NetworkClient {
|
||||
const NetworkClient();
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
class Breakpoints {
|
||||
static const double mobile = 720;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
abstract final class ByteSizeFormatter {
|
||||
static const _units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
|
||||
static String format(int bytes) {
|
||||
if (bytes <= 0) return '0 B';
|
||||
|
||||
var value = bytes.toDouble();
|
||||
var unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < _units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
// Bytes are whole values. Scaled binary units keep at most two decimal
|
||||
// places and omit trailing zeroes (for example: 1.5 MB, 1.25 MB, 2 MB).
|
||||
final formattedValue = unitIndex == 0 ? value.round().toString() : _trimFraction(value.toStringAsFixed(2));
|
||||
return '$formattedValue ${_units[unitIndex]}';
|
||||
}
|
||||
|
||||
static String _trimFraction(String value) {
|
||||
return value.replaceFirst(RegExp(r'0+$'), '').replaceFirst(RegExp(r'\.$'), '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import 'content_uri_resolver_stub.dart' if (dart.library.io) 'content_uri_resolver_io.dart' as implementation;
|
||||
|
||||
/// Resolves a platform content URI into a local temporary file.
|
||||
abstract final class ContentUriResolver {
|
||||
static Future<String> copyToCache(Uri uri) => implementation.copyToCache(uri);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:uri_content/uri_content.dart';
|
||||
|
||||
Future<String> copyToCache(Uri uri) async {
|
||||
if (uri.scheme != 'content') {
|
||||
throw ArgumentError.value(uri, 'uri', 'Expected an Android content URI');
|
||||
}
|
||||
if (!Platform.isAndroid) {
|
||||
throw UnsupportedError('content URIs are only supported on Android');
|
||||
}
|
||||
|
||||
final importDirectory = Directory(path.join((await getTemporaryDirectory()).path, 'torrent-imports'));
|
||||
await importDirectory.create(recursive: true);
|
||||
final output = File(path.join(importDirectory.path, 'gopeed-${DateTime.now().microsecondsSinceEpoch}.torrent'));
|
||||
final sink = output.openWrite();
|
||||
|
||||
try {
|
||||
await sink.addStream(UriContent().getContentStream(uri));
|
||||
await sink.close();
|
||||
} catch (error) {
|
||||
await sink.close();
|
||||
if (await output.exists()) await output.delete();
|
||||
rethrow;
|
||||
}
|
||||
|
||||
return output.path;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Future<String> copyToCache(Uri uri) {
|
||||
throw UnsupportedError('content URIs are not supported on this platform');
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import 'file_explorer_stub.dart' if (dart.library.io) 'file_explorer_native.dart' as implementation;
|
||||
|
||||
abstract final class FileExplorer {
|
||||
static Future<bool> open(String filePath) => implementation.open(filePath);
|
||||
|
||||
static Future<bool> reveal(String filePath) => implementation.reveal(filePath);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:open_dir/open_dir.dart';
|
||||
import 'package:open_filex/open_filex.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
Future<bool> open(String filePath) async {
|
||||
try {
|
||||
if (!await FileSystemEntity.isFile(filePath) && !await FileSystemEntity.isDirectory(filePath)) {
|
||||
return false;
|
||||
}
|
||||
final result = await OpenFilex.open(filePath);
|
||||
return result.type == ResultType.done;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> reveal(String filePath) async {
|
||||
try {
|
||||
if (!(Platform.isWindows || Platform.isMacOS || Platform.isLinux)) {
|
||||
return open(filePath);
|
||||
}
|
||||
|
||||
if (await FileSystemEntity.isFile(filePath)) {
|
||||
return await OpenDir().openNativeDir(
|
||||
path: path.dirname(filePath),
|
||||
highlightedFileName: path.basename(filePath),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
if (await FileSystemEntity.isDirectory(filePath)) {
|
||||
return await OpenDir().openNativeDir(path: filePath) ?? false;
|
||||
}
|
||||
|
||||
final parentPath = path.dirname(filePath);
|
||||
if (await FileSystemEntity.isDirectory(parentPath)) {
|
||||
return await OpenDir().openNativeDir(path: parentPath) ?? false;
|
||||
}
|
||||
return false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Future<bool> open(String filePath) async => false;
|
||||
|
||||
Future<bool> reveal(String filePath) async => false;
|
||||
@@ -0,0 +1,8 @@
|
||||
import 'tcp_port_checker_stub.dart' if (dart.library.io) 'tcp_port_checker_native.dart' as implementation;
|
||||
|
||||
/// Returns whether a TCP connection can be established to [host]:[port].
|
||||
///
|
||||
/// The settings page uses this before saving a changed API listen address,
|
||||
/// matching the legacy UI's occupied-port check. Unsupported platforms return
|
||||
/// false so validation never blocks configuration that cannot be probed locally.
|
||||
Future<bool> isTcpPortInUse(String host, int port) => implementation.isTcpPortInUse(host, port);
|
||||
@@ -0,0 +1,11 @@
|
||||
import 'dart:io';
|
||||
|
||||
Future<bool> isTcpPortInUse(String host, int port) async {
|
||||
try {
|
||||
final socket = await Socket.connect(host, port, timeout: const Duration(seconds: 3));
|
||||
await socket.close();
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Future<bool> isTcpPortInUse(String host, int port) async => false;
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
String softWrapAnywhere(String value) => value.characters.join('\u200B');
|
||||
@@ -0,0 +1,28 @@
|
||||
class FormattedTransferRate {
|
||||
const FormattedTransferRate({required this.value, required this.unit});
|
||||
|
||||
final String value;
|
||||
final String unit;
|
||||
|
||||
String get text => '$value $unit';
|
||||
}
|
||||
|
||||
abstract final class TransferRateFormatter {
|
||||
static const _units = ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s'];
|
||||
|
||||
static FormattedTransferRate format(int bytesPerSecond) {
|
||||
var value = bytesPerSecond < 0 ? 0.0 : bytesPerSecond.toDouble();
|
||||
var unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < _units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
|
||||
final formattedValue = unitIndex == 0 ? value.round().toString() : _trimFraction(value.toStringAsFixed(2));
|
||||
return FormattedTransferRate(value: formattedValue, unit: _units[unitIndex]);
|
||||
}
|
||||
|
||||
static String _trimFraction(String value) {
|
||||
return value.replaceFirst(RegExp(r'0+$'), '').replaceFirst(RegExp(r'\.$'), '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
class AppWindowAppearance {
|
||||
const AppWindowAppearance({required this.themeMode, required this.themeColor, required this.locale});
|
||||
|
||||
const AppWindowAppearance.defaults() : themeMode = 'system', themeColor = 'green', locale = '';
|
||||
|
||||
factory AppWindowAppearance.fromJson(Map<String, dynamic> json) {
|
||||
return AppWindowAppearance(
|
||||
themeMode: (json['themeMode'] ?? 'system').toString(),
|
||||
themeColor: (json['themeColor'] ?? 'green').toString(),
|
||||
locale: (json['locale'] ?? '').toString(),
|
||||
);
|
||||
}
|
||||
|
||||
final String themeMode;
|
||||
final String themeColor;
|
||||
final String locale;
|
||||
|
||||
Map<String, dynamic> toJson() => {'themeMode': themeMode, 'themeColor': themeColor, 'locale': locale};
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is AppWindowAppearance &&
|
||||
other.themeMode == themeMode &&
|
||||
other.themeColor == themeColor &&
|
||||
other.locale == locale;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(themeMode, themeColor, locale);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform;
|
||||
import 'package:flutter/material.dart' show Colors;
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
|
||||
import '../../database/database.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import 'app_window_chrome.dart';
|
||||
import 'app_window_payload.dart';
|
||||
|
||||
class AppWindowBootstrap {
|
||||
static Future<void> setupMainWindow({bool hidden = false}) async {
|
||||
if (!AppWindowChrome.isDesktopWindow) {
|
||||
return;
|
||||
}
|
||||
|
||||
await windowManager.ensureInitialized();
|
||||
|
||||
final windowState = Database.instance.getWindowState();
|
||||
final windowOptions = WindowOptions(
|
||||
size: Size(windowState?.width ?? 1024, windowState?.height ?? 768),
|
||||
center: true,
|
||||
skipTaskbar: false,
|
||||
backgroundColor: Colors.transparent,
|
||||
titleBarStyle: TitleBarStyle.hidden,
|
||||
);
|
||||
|
||||
windowManager.waitUntilReadyToShow(windowOptions, () async {
|
||||
if (AppWindowChrome.usesCustomChrome) {
|
||||
await windowManager.setAsFrameless();
|
||||
}
|
||||
await windowManager.setHasShadow(true);
|
||||
if (!hidden) {
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static Future<void> setupSubWindow(AppWindowType type, {String localeConfig = ''}) async {
|
||||
if (!AppWindowChrome.isDesktopWindow) {
|
||||
return;
|
||||
}
|
||||
|
||||
await windowManager.ensureInitialized();
|
||||
final title = subWindowTitle(type, appLocalizationsFor(localeConfig));
|
||||
|
||||
final options = switch (type) {
|
||||
AppWindowType.createTask => WindowOptions(
|
||||
size: Size(820, 620),
|
||||
center: true,
|
||||
skipTaskbar: false,
|
||||
backgroundColor: Colors.transparent,
|
||||
title: title,
|
||||
titleBarStyle: TitleBarStyle.hidden,
|
||||
),
|
||||
_ => WindowOptions(
|
||||
size: Size(900, 640),
|
||||
center: true,
|
||||
skipTaskbar: false,
|
||||
backgroundColor: Colors.transparent,
|
||||
title: title,
|
||||
titleBarStyle: TitleBarStyle.hidden,
|
||||
),
|
||||
};
|
||||
|
||||
windowManager.waitUntilReadyToShow(options, () async {
|
||||
if (AppWindowChrome.usesCustomChrome) {
|
||||
await windowManager.setAsFrameless();
|
||||
}
|
||||
await windowManager.setTitle(title);
|
||||
await windowManager.setHasShadow(true);
|
||||
await _showSubWindowInForeground();
|
||||
});
|
||||
}
|
||||
|
||||
static String subWindowTitle(AppWindowType type, AppLocalizations l10n) {
|
||||
return switch (type) {
|
||||
AppWindowType.createTask => '${l10n.create} - Gopeed',
|
||||
_ => l10n.appTitle,
|
||||
};
|
||||
}
|
||||
|
||||
static Future<void> _showSubWindowInForeground() async {
|
||||
if (defaultTargetPlatform != TargetPlatform.windows) {
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
// SetForegroundWindow may be rejected after the browser regains focus
|
||||
// while the child Flutter engine is starting. A brief topmost pulse keeps
|
||||
// the user-initiated create window visible without making it permanently
|
||||
// always-on-top.
|
||||
var pulsing = false;
|
||||
try {
|
||||
await windowManager.setAlwaysOnTop(true);
|
||||
pulsing = true;
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 180));
|
||||
} finally {
|
||||
if (pulsing) {
|
||||
await windowManager.setAlwaysOnTop(false);
|
||||
}
|
||||
}
|
||||
await windowManager.focus();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
abstract final class AppWindowChrome {
|
||||
static bool get isDesktopWindow =>
|
||||
!kIsWeb &&
|
||||
(defaultTargetPlatform == TargetPlatform.windows ||
|
||||
defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.linux);
|
||||
|
||||
static bool get usesCustomChrome =>
|
||||
!kIsWeb && (defaultTargetPlatform == TargetPlatform.windows || defaultTargetPlatform == TargetPlatform.linux);
|
||||
|
||||
static bool get reservesHeaderInset => isDesktopWindow;
|
||||
|
||||
static bool get clipsRoundedCorners => !kIsWeb && defaultTargetPlatform == TargetPlatform.windows;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'package:flutter/material.dart' show Colors;
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
|
||||
import '../../shared/widgets/window/desktop_window_header.dart';
|
||||
import 'app_window_chrome.dart';
|
||||
|
||||
const double kWindowCornerRadius = 12;
|
||||
|
||||
class AppWindowFrame extends StatelessWidget {
|
||||
const AppWindowFrame({super.key, required this.child});
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget framedChild = child;
|
||||
|
||||
if (AppWindowChrome.usesCustomChrome) {
|
||||
framedChild = Stack(
|
||||
children: [
|
||||
Positioned.fill(child: child),
|
||||
const Positioned(top: 0, left: 0, right: 0, child: DesktopWindowHeader()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (AppWindowChrome.clipsRoundedCorners) {
|
||||
framedChild = ClipRRect(borderRadius: BorderRadius.circular(kWindowCornerRadius), child: framedChild);
|
||||
}
|
||||
|
||||
if (AppWindowChrome.clipsRoundedCorners) {
|
||||
framedChild = DecoratedBox(
|
||||
decoration: const BoxDecoration(color: Colors.transparent),
|
||||
child: framedChild,
|
||||
);
|
||||
}
|
||||
|
||||
if (AppWindowChrome.usesCustomChrome) {
|
||||
framedChild = DragToResizeArea(resizeEdgeSize: 6, child: framedChild);
|
||||
}
|
||||
|
||||
return framedChild;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import 'package:desktop_multi_window/desktop_multi_window.dart';
|
||||
|
||||
import 'app_window_payload.dart';
|
||||
|
||||
class AppWindowLaunchContext {
|
||||
const AppWindowLaunchContext._({required this.isSubWindow, required this.payload, this.windowId});
|
||||
|
||||
factory AppWindowLaunchContext.main() {
|
||||
return AppWindowLaunchContext._(isSubWindow: false, payload: AppWindowPayload.main());
|
||||
}
|
||||
|
||||
factory AppWindowLaunchContext.subWindow({required String windowId, required AppWindowPayload payload}) {
|
||||
return AppWindowLaunchContext._(isSubWindow: true, windowId: windowId, payload: payload);
|
||||
}
|
||||
|
||||
factory AppWindowLaunchContext.fromArgs(List<String> args) {
|
||||
if (args.length >= 2 && args.first == 'multi_window') {
|
||||
final windowId = args[1];
|
||||
final payload = args.length >= 3 ? AppWindowPayload.fromRaw(args[2]) : AppWindowPayload.main();
|
||||
return AppWindowLaunchContext.subWindow(windowId: windowId, payload: payload);
|
||||
}
|
||||
|
||||
return AppWindowLaunchContext.main();
|
||||
}
|
||||
|
||||
final bool isSubWindow;
|
||||
final String? windowId;
|
||||
final AppWindowPayload payload;
|
||||
|
||||
WindowController? buildController() {
|
||||
if (!isSubWindow || windowId == null) {
|
||||
return null;
|
||||
}
|
||||
return WindowController.fromWindowId(windowId!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:desktop_multi_window/desktop_multi_window.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../util/log_util.dart';
|
||||
import '../capabilities/app_capabilities.dart';
|
||||
import 'app_window_payload.dart';
|
||||
import 'window_capability_transport.dart';
|
||||
|
||||
class AppWindowLauncher {
|
||||
static Future<bool> openCreateTaskWindow({CreateTask? createTask}) async {
|
||||
if (kIsWeb || !(Platform.isWindows || Platform.isMacOS || Platform.isLinux)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await AppWindowCapabilityHost.instance.start(LocalAppCapabilities.instance.registry);
|
||||
final payload = AppWindowPayload.createTask(createTask: createTask?.toJson());
|
||||
// Every request deliberately creates a new child window. Create-task
|
||||
// windows are independent and are never reused.
|
||||
await WindowController.create(WindowConfiguration(arguments: payload.toRaw(), hiddenAtLaunch: true));
|
||||
// Keep the native window hidden until the child engine has applied its
|
||||
// final size, centered position, chrome, and foreground behavior in
|
||||
// AppWindowBootstrap.setupSubWindow.
|
||||
return true;
|
||||
} catch (error, stackTrace) {
|
||||
try {
|
||||
logger.w('create task window failed', error, stackTrace);
|
||||
} catch (_) {
|
||||
debugPrint('create task window failed: $error');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import 'dart:convert';
|
||||
|
||||
enum AppWindowType { main, createTask }
|
||||
|
||||
class AppWindowPayload {
|
||||
const AppWindowPayload({required this.type, this.data = const {}});
|
||||
|
||||
factory AppWindowPayload.main() => const AppWindowPayload(type: AppWindowType.main);
|
||||
|
||||
factory AppWindowPayload.createTask({Map<String, dynamic>? createTask}) => AppWindowPayload(
|
||||
type: AppWindowType.createTask,
|
||||
data: {
|
||||
...?createTask == null ? null : {'createTask': createTask},
|
||||
},
|
||||
);
|
||||
|
||||
factory AppWindowPayload.fromRaw(String raw) {
|
||||
if (raw.trim().isEmpty) {
|
||||
return AppWindowPayload.main();
|
||||
}
|
||||
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
final type = switch ((decoded['type'] ?? '').toString()) {
|
||||
'create_task' => AppWindowType.createTask,
|
||||
_ => AppWindowType.main,
|
||||
};
|
||||
return AppWindowPayload(type: type, data: decoded);
|
||||
}
|
||||
} catch (_) {
|
||||
// Ignore invalid payload and fallback to main.
|
||||
}
|
||||
|
||||
return AppWindowPayload.main();
|
||||
}
|
||||
|
||||
final AppWindowType type;
|
||||
final Map<String, dynamic> data;
|
||||
|
||||
Map<String, dynamic>? get createTask {
|
||||
final raw = data['createTask'];
|
||||
return raw is Map<String, dynamic> ? raw : null;
|
||||
}
|
||||
|
||||
String toRaw() {
|
||||
return jsonEncode({
|
||||
'type': switch (type) {
|
||||
AppWindowType.main => 'main',
|
||||
AppWindowType.createTask => 'create_task',
|
||||
},
|
||||
...data,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:desktop_multi_window/desktop_multi_window.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../capabilities/app_capabilities.dart';
|
||||
import '../capabilities/capability_rpc.dart';
|
||||
import 'app_window_appearance.dart';
|
||||
|
||||
abstract final class AppWindowRpcProtocol {
|
||||
static const channelName = 'gopeed.app.capabilities.v1';
|
||||
static const call = 'capability.call';
|
||||
static const bootstrap = 'window.bootstrap';
|
||||
static const subscribe = 'window.subscribe';
|
||||
static const unsubscribe = 'window.unsubscribe';
|
||||
static const event = 'window.event';
|
||||
static const appearanceChanged = 'appearance.changed';
|
||||
}
|
||||
|
||||
const _hostChannel = WindowMethodChannel(AppWindowRpcProtocol.channelName, mode: ChannelMode.unidirectional);
|
||||
|
||||
class WindowCapabilityInvoker implements CapabilityInvoker {
|
||||
const WindowCapabilityInvoker(this.codecs);
|
||||
|
||||
final RpcCodecRegistry codecs;
|
||||
|
||||
@override
|
||||
Future<R> invoke<P, R>(RpcMethod<P, R> method, P params) async {
|
||||
final raw = await _hostChannel.invokeMethod<dynamic>(AppWindowRpcProtocol.call, {
|
||||
'operation': method.name,
|
||||
'payload': codecs.encode(params),
|
||||
});
|
||||
final response = codecs.decode<Map<String, dynamic>>(raw);
|
||||
if (response['ok'] != true) {
|
||||
final error = codecs.decode<Map<String, dynamic>>(response['error']);
|
||||
throw CapabilityException(
|
||||
(error['code'] ?? 'remote_error').toString(),
|
||||
(error['message'] ?? 'Remote capability failed').toString(),
|
||||
error['details'],
|
||||
);
|
||||
}
|
||||
return codecs.decode<R>(response['data']);
|
||||
}
|
||||
}
|
||||
|
||||
class AppWindowCapabilityHost {
|
||||
AppWindowCapabilityHost._();
|
||||
|
||||
static final instance = AppWindowCapabilityHost._();
|
||||
|
||||
CapabilityRegistry? _registry;
|
||||
AppWindowAppearance _appearance = const AppWindowAppearance.defaults();
|
||||
final Map<String, WindowController> _subscribers = {};
|
||||
|
||||
bool get started => _registry != null;
|
||||
|
||||
Future<void> start(CapabilityRegistry registry) async {
|
||||
if (_registry != null) return;
|
||||
_registry = registry;
|
||||
await _hostChannel.setMethodCallHandler(_handleCall);
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
_registry = null;
|
||||
_subscribers.clear();
|
||||
await _hostChannel.setMethodCallHandler(null);
|
||||
}
|
||||
|
||||
void updateAppearance(AppWindowAppearance appearance) {
|
||||
if (_appearance == appearance) return;
|
||||
_appearance = appearance;
|
||||
unawaited(_broadcastAppearance());
|
||||
}
|
||||
|
||||
Future<dynamic> _handleCall(MethodCall call) async {
|
||||
try {
|
||||
switch (call.method) {
|
||||
case AppWindowRpcProtocol.call:
|
||||
final args = _map(call.arguments);
|
||||
final registry = _registry;
|
||||
if (registry == null) {
|
||||
throw const CapabilityException('host_unavailable', 'Main window capabilities are not ready');
|
||||
}
|
||||
final data = await registry.invoke((args['operation'] ?? '').toString(), args['payload']);
|
||||
return {'ok': true, 'data': data};
|
||||
case AppWindowRpcProtocol.bootstrap:
|
||||
return _appearance.toJson();
|
||||
case AppWindowRpcProtocol.subscribe:
|
||||
final windowId = (_map(call.arguments)['windowId'] ?? '').toString();
|
||||
if (windowId.isEmpty) {
|
||||
throw const CapabilityException('invalid_window', 'Missing child window id');
|
||||
}
|
||||
final controller = WindowController.fromWindowId(windowId);
|
||||
_subscribers[windowId] = controller;
|
||||
scheduleMicrotask(() => _sendAppearance(windowId, controller));
|
||||
return null;
|
||||
case AppWindowRpcProtocol.unsubscribe:
|
||||
final windowId = (_map(call.arguments)['windowId'] ?? '').toString();
|
||||
_subscribers.remove(windowId);
|
||||
return null;
|
||||
default:
|
||||
throw CapabilityException('method_not_found', 'Window RPC method not found: ${call.method}');
|
||||
}
|
||||
} on CapabilityException catch (error) {
|
||||
if (call.method == AppWindowRpcProtocol.call) {
|
||||
return {
|
||||
'ok': false,
|
||||
'error': {'code': error.code, 'message': error.message, 'details': error.details},
|
||||
};
|
||||
}
|
||||
rethrow;
|
||||
} catch (error) {
|
||||
if (call.method == AppWindowRpcProtocol.call) {
|
||||
return {
|
||||
'ok': false,
|
||||
'error': {'code': 'internal_error', 'message': error.toString()},
|
||||
};
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _broadcastAppearance() async {
|
||||
final subscribers = Map<String, WindowController>.of(_subscribers);
|
||||
await Future.wait([for (final entry in subscribers.entries) _sendAppearance(entry.key, entry.value)]);
|
||||
}
|
||||
|
||||
Future<void> _sendAppearance(String windowId, WindowController controller) async {
|
||||
try {
|
||||
await controller.invokeMethod<void>(AppWindowRpcProtocol.event, {
|
||||
'name': AppWindowRpcProtocol.appearanceChanged,
|
||||
'data': _appearance.toJson(),
|
||||
});
|
||||
} catch (_) {
|
||||
_subscribers.remove(windowId);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _map(Object? value) {
|
||||
if (value is! Map) return const {};
|
||||
return {for (final entry in value.entries) entry.key.toString(): entry.value};
|
||||
}
|
||||
}
|
||||
|
||||
class ChildWindowSession {
|
||||
ChildWindowSession._(this.controller, this.codecs)
|
||||
: capabilities = AppCapabilities(WindowCapabilityInvoker(codecs)),
|
||||
appearance = ValueNotifier(const AppWindowAppearance.defaults());
|
||||
|
||||
static Future<ChildWindowSession> connect(WindowController controller) async {
|
||||
final session = ChildWindowSession._(controller, createAppCapabilityCodecs());
|
||||
await session._initialize();
|
||||
return session;
|
||||
}
|
||||
|
||||
final WindowController controller;
|
||||
final RpcCodecRegistry codecs;
|
||||
final AppCapabilities capabilities;
|
||||
final ValueNotifier<AppWindowAppearance> appearance;
|
||||
|
||||
Future<void> _initialize() async {
|
||||
await controller.setWindowMethodHandler(_handleWindowCall);
|
||||
final initial = await _hostChannel.invokeMethod<dynamic>(AppWindowRpcProtocol.bootstrap);
|
||||
appearance.value = codecs.decode<AppWindowAppearance>(initial);
|
||||
await _hostChannel.invokeMethod<void>(AppWindowRpcProtocol.subscribe, {'windowId': controller.windowId});
|
||||
}
|
||||
|
||||
Future<dynamic> _handleWindowCall(MethodCall call) async {
|
||||
if (call.method != AppWindowRpcProtocol.event) return null;
|
||||
final args = codecs.decode<Map<String, dynamic>>(call.arguments);
|
||||
if (args['name'] == AppWindowRpcProtocol.appearanceChanged) {
|
||||
appearance.value = codecs.decode<AppWindowAppearance>(args['data']);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
unawaited(controller.setWindowMethodHandler(null));
|
||||
unawaited(_hostChannel.invokeMethod<void>(AppWindowRpcProtocol.unsubscribe, {'windowId': controller.windowId}));
|
||||
appearance.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user