repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/localsend/app/lib/pages | mirrored_repositories/localsend/app/lib/pages/debug/debug_page.dart | import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/pages/debug/discovery_debug_page.dart';
import 'package:localsend_app/pages/debug/http_logs_page.dart';
import 'package:localsend_app/pages/debug/security_debug_page.dart';
import 'package:localsend_app/provider/app_arguments_provider.dart';
import 'package:localsend_app/provider/persistence_provider.dart';
import 'package:localsend_app/widget/debug_entry.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
class DebugPage extends StatelessWidget {
const DebugPage({super.key});
@override
Widget build(BuildContext context) {
final appArguments = context.ref.watch(appArgumentsProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Debugging'),
),
body: ListView(
padding: const EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 30),
children: [
DebugEntry(
name: 'Debug Mode',
value: kDebugMode.toString(),
),
DebugEntry(
name: 'App Arguments',
value: appArguments.isEmpty ? null : appArguments.join(' '),
),
DebugEntry(
name: 'Dart SDK',
value: Platform.version,
),
const SizedBox(height: 20),
const Text('More', style: DebugEntry.headerStyle),
const SizedBox(height: 5),
Wrap(
spacing: 10,
runSpacing: 10,
children: [
FilledButton(
onPressed: () async => context.push(() => const SecurityDebugPage()),
child: const Text('Security'),
),
FilledButton(
onPressed: () async => context.push(() => const DiscoveryDebugPage()),
child: const Text('Discovery'),
),
FilledButton(
onPressed: () async => context.push(() => const HttpLogsPage()),
child: const Text('HTTP Logs'),
),
if (kDebugMode)
FilledButton(
onPressed: () async => context.push(() => const RefenaTracingPage()),
child: const Text('Refena Tracing'),
),
FilledButton(
onPressed: () async => await context.ref.read(persistenceProvider).clear(),
child: const Text('Clear settings'),
),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/pages | mirrored_repositories/localsend/app/lib/pages/debug/security_debug_page.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/provider/security_provider.dart';
import 'package:localsend_app/widget/debug_entry.dart';
import 'package:localsend_app/widget/responsive_list_view.dart';
import 'package:refena_flutter/refena_flutter.dart';
class SecurityDebugPage extends StatelessWidget {
const SecurityDebugPage({super.key});
@override
Widget build(BuildContext context) {
final securityContext = context.ref.watch(securityProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Security Debugging'),
),
body: ResponsiveListView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
maxWidth: 700,
children: [
Row(
children: [
FilledButton(
onPressed: () async => await context.ref.redux(securityProvider).dispatchAsync(ResetSecurityContextAction()),
child: const Text('Reset'),
),
],
),
DebugEntry(
name: 'Certificate SHA-256 (fingerprint)',
value: securityContext.certificateHash,
),
DebugEntry(
name: 'Certificate',
value: securityContext.certificate,
),
DebugEntry(
name: 'Private Key',
value: securityContext.privateKey,
),
DebugEntry(
name: 'Public Key',
value: securityContext.publicKey,
),
],
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/pages | mirrored_repositories/localsend/app/lib/pages/debug/discovery_debug_page.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:localsend_app/provider/logging/discovery_logs_provider.dart';
import 'package:localsend_app/provider/network/nearby_devices_provider.dart';
import 'package:localsend_app/widget/copyable_text.dart';
import 'package:localsend_app/widget/responsive_list_view.dart';
import 'package:refena_flutter/refena_flutter.dart';
final _dateFormat = DateFormat.Hms();
class DiscoveryDebugPage extends StatelessWidget {
const DiscoveryDebugPage({super.key});
@override
Widget build(BuildContext context) {
final ref = context.ref;
final logs = ref.watch(discoveryLoggerProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Discovery Debugging'),
),
body: ResponsiveListView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
children: [
Row(
children: [
ElevatedButton(
onPressed: () => ref.redux(nearbyDevicesProvider).dispatch(StartMulticastScan()),
child: const Text('Announce'),
),
const SizedBox(width: 20),
ElevatedButton(
onPressed: () => ref.notifier(discoveryLoggerProvider).clear(),
child: const Text('Clear'),
),
],
),
const SizedBox(height: 20),
...logs.map((log) => CopyableText(
prefix: TextSpan(
text: '[${_dateFormat.format(log.timestamp)}] ',
style: const TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
),
),
name: log.log,
value: log.log,
)),
],
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/pages | mirrored_repositories/localsend/app/lib/pages/debug/http_logs_page.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:localsend_app/provider/logging/http_logs_provider.dart';
import 'package:localsend_app/widget/copyable_text.dart';
import 'package:localsend_app/widget/responsive_list_view.dart';
import 'package:refena_flutter/refena_flutter.dart';
final _dateFormat = DateFormat.Hms();
class HttpLogsPage extends StatelessWidget {
const HttpLogsPage({super.key});
@override
Widget build(BuildContext context) {
final logs = context.ref.watch(httpLogsProvider);
return Scaffold(
appBar: AppBar(
title: const Text('HTTP Logs'),
),
body: ResponsiveListView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
children: [
Row(
children: [
ElevatedButton(
onPressed: () => context.ref.notifier(httpLogsProvider).clear(),
child: const Text('Clear'),
),
],
),
const SizedBox(height: 20),
...logs.map((log) => CopyableText(
prefix: TextSpan(
text: '[${_dateFormat.format(log.timestamp)}] ',
style: const TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
),
),
name: log.log,
value: log.log,
)),
],
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/model/cross_file.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'cross_file.dart';
class CrossFileMapper extends ClassMapperBase<CrossFile> {
CrossFileMapper._();
static CrossFileMapper? _instance;
static CrossFileMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = CrossFileMapper._());
FileTypeMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'CrossFile';
static String _$name(CrossFile v) => v.name;
static const Field<CrossFile, String> _f$name = Field('name', _$name);
static FileType _$fileType(CrossFile v) => v.fileType;
static const Field<CrossFile, FileType> _f$fileType = Field('fileType', _$fileType);
static int _$size(CrossFile v) => v.size;
static const Field<CrossFile, int> _f$size = Field('size', _$size);
static Uint8List? _$thumbnail(CrossFile v) => v.thumbnail;
static const Field<CrossFile, Uint8List> _f$thumbnail = Field('thumbnail', _$thumbnail);
static AssetEntity? _$asset(CrossFile v) => v.asset;
static const Field<CrossFile, AssetEntity> _f$asset = Field('asset', _$asset);
static String? _$path(CrossFile v) => v.path;
static const Field<CrossFile, String> _f$path = Field('path', _$path);
static List<int>? _$bytes(CrossFile v) => v.bytes;
static const Field<CrossFile, List<int>> _f$bytes = Field('bytes', _$bytes);
@override
final MappableFields<CrossFile> fields = const {
#name: _f$name,
#fileType: _f$fileType,
#size: _f$size,
#thumbnail: _f$thumbnail,
#asset: _f$asset,
#path: _f$path,
#bytes: _f$bytes,
};
static CrossFile _instantiate(DecodingData data) {
return CrossFile(
name: data.dec(_f$name),
fileType: data.dec(_f$fileType),
size: data.dec(_f$size),
thumbnail: data.dec(_f$thumbnail),
asset: data.dec(_f$asset),
path: data.dec(_f$path),
bytes: data.dec(_f$bytes));
}
@override
final Function instantiate = _instantiate;
static CrossFile fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<CrossFile>(map);
}
static CrossFile deserialize(String json) {
return ensureInitialized().decodeJson<CrossFile>(json);
}
}
mixin CrossFileMappable {
String serialize() {
return CrossFileMapper.ensureInitialized().encodeJson<CrossFile>(this as CrossFile);
}
Map<String, dynamic> toJson() {
return CrossFileMapper.ensureInitialized().encodeMap<CrossFile>(this as CrossFile);
}
CrossFileCopyWith<CrossFile, CrossFile, CrossFile> get copyWith => _CrossFileCopyWithImpl(this as CrossFile, $identity, $identity);
@override
String toString() {
return CrossFileMapper.ensureInitialized().stringifyValue(this as CrossFile);
}
@override
bool operator ==(Object other) {
return identical(this, other) || (runtimeType == other.runtimeType && CrossFileMapper.ensureInitialized().isValueEqual(this as CrossFile, other));
}
@override
int get hashCode {
return CrossFileMapper.ensureInitialized().hashValue(this as CrossFile);
}
}
extension CrossFileValueCopy<$R, $Out> on ObjectCopyWith<$R, CrossFile, $Out> {
CrossFileCopyWith<$R, CrossFile, $Out> get $asCrossFile => $base.as((v, t, t2) => _CrossFileCopyWithImpl(v, t, t2));
}
abstract class CrossFileCopyWith<$R, $In extends CrossFile, $Out> implements ClassCopyWith<$R, $In, $Out> {
ListCopyWith<$R, int, ObjectCopyWith<$R, int, int>>? get bytes;
$R call({String? name, FileType? fileType, int? size, Uint8List? thumbnail, AssetEntity? asset, String? path, List<int>? bytes});
CrossFileCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _CrossFileCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, CrossFile, $Out> implements CrossFileCopyWith<$R, CrossFile, $Out> {
_CrossFileCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<CrossFile> $mapper = CrossFileMapper.ensureInitialized();
@override
ListCopyWith<$R, int, ObjectCopyWith<$R, int, int>>? get bytes =>
$value.bytes != null ? ListCopyWith($value.bytes!, (v, t) => ObjectCopyWith(v, $identity, t), (v) => call(bytes: v)) : null;
@override
$R call(
{String? name,
FileType? fileType,
int? size,
Object? thumbnail = $none,
Object? asset = $none,
Object? path = $none,
Object? bytes = $none}) =>
$apply(FieldCopyWithData({
if (name != null) #name: name,
if (fileType != null) #fileType: fileType,
if (size != null) #size: size,
if (thumbnail != $none) #thumbnail: thumbnail,
if (asset != $none) #asset: asset,
if (path != $none) #path: path,
if (bytes != $none) #bytes: bytes
}));
@override
CrossFile $make(CopyWithData data) => CrossFile(
name: data.get(#name, or: $value.name),
fileType: data.get(#fileType, or: $value.fileType),
size: data.get(#size, or: $value.size),
thumbnail: data.get(#thumbnail, or: $value.thumbnail),
asset: data.get(#asset, or: $value.asset),
path: data.get(#path, or: $value.path),
bytes: data.get(#bytes, or: $value.bytes));
@override
CrossFileCopyWith<$R2, CrossFile, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _CrossFileCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/model/send_mode.dart | enum SendMode {
single, // 1:1 file transfer
multiple, // 1:n file transfer
link, // 1:n file transfer but receiver needs to initiate
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/model/log_entry.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'log_entry.dart';
class LogEntryMapper extends ClassMapperBase<LogEntry> {
LogEntryMapper._();
static LogEntryMapper? _instance;
static LogEntryMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = LogEntryMapper._());
}
return _instance!;
}
@override
final String id = 'LogEntry';
static DateTime _$timestamp(LogEntry v) => v.timestamp;
static const Field<LogEntry, DateTime> _f$timestamp = Field('timestamp', _$timestamp);
static String _$log(LogEntry v) => v.log;
static const Field<LogEntry, String> _f$log = Field('log', _$log);
@override
final MappableFields<LogEntry> fields = const {
#timestamp: _f$timestamp,
#log: _f$log,
};
static LogEntry _instantiate(DecodingData data) {
return LogEntry(timestamp: data.dec(_f$timestamp), log: data.dec(_f$log));
}
@override
final Function instantiate = _instantiate;
static LogEntry fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<LogEntry>(map);
}
static LogEntry deserialize(String json) {
return ensureInitialized().decodeJson<LogEntry>(json);
}
}
mixin LogEntryMappable {
String serialize() {
return LogEntryMapper.ensureInitialized().encodeJson<LogEntry>(this as LogEntry);
}
Map<String, dynamic> toJson() {
return LogEntryMapper.ensureInitialized().encodeMap<LogEntry>(this as LogEntry);
}
LogEntryCopyWith<LogEntry, LogEntry, LogEntry> get copyWith => _LogEntryCopyWithImpl(this as LogEntry, $identity, $identity);
@override
String toString() {
return LogEntryMapper.ensureInitialized().stringifyValue(this as LogEntry);
}
@override
bool operator ==(Object other) {
return identical(this, other) || (runtimeType == other.runtimeType && LogEntryMapper.ensureInitialized().isValueEqual(this as LogEntry, other));
}
@override
int get hashCode {
return LogEntryMapper.ensureInitialized().hashValue(this as LogEntry);
}
}
extension LogEntryValueCopy<$R, $Out> on ObjectCopyWith<$R, LogEntry, $Out> {
LogEntryCopyWith<$R, LogEntry, $Out> get $asLogEntry => $base.as((v, t, t2) => _LogEntryCopyWithImpl(v, t, t2));
}
abstract class LogEntryCopyWith<$R, $In extends LogEntry, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call({DateTime? timestamp, String? log});
LogEntryCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _LogEntryCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, LogEntry, $Out> implements LogEntryCopyWith<$R, LogEntry, $Out> {
_LogEntryCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<LogEntry> $mapper = LogEntryMapper.ensureInitialized();
@override
$R call({DateTime? timestamp, String? log}) =>
$apply(FieldCopyWithData({if (timestamp != null) #timestamp: timestamp, if (log != null) #log: log}));
@override
LogEntry $make(CopyWithData data) => LogEntry(timestamp: data.get(#timestamp, or: $value.timestamp), log: data.get(#log, or: $value.log));
@override
LogEntryCopyWith<$R2, LogEntry, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _LogEntryCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/model/cross_file.dart | import 'dart:typed_data';
import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
part 'cross_file.mapper.dart';
/// Common file model to avoid any third party libraries in the core logic.
/// This model is used during the file selection phase.
@MappableClass()
class CrossFile with CrossFileMappable {
final String name;
final FileType fileType;
final int size;
final Uint8List? thumbnail;
final AssetEntity? asset; // for thumbnails
final String? path;
final List<int>? bytes; // if type message, then UTF-8 encoded
const CrossFile({
required this.name,
required this.fileType,
required this.size,
required this.thumbnail,
required this.asset,
required this.path,
required this.bytes,
});
/// Custom toString() to avoid printing the bytes.
@override
String toString() {
return 'CrossFile(name: $name, fileType: $fileType, size: $size, thumbnail: ${thumbnail != null ? thumbnail!.length : 'null'}, asset: $asset, path: $path, bytes: ${bytes != null ? bytes!.length : 'null'})';
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/model/log_entry.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'log_entry.mapper.dart';
@MappableClass()
class LogEntry with LogEntryMappable {
final DateTime timestamp;
final String log;
const LogEntry({
required this.timestamp,
required this.log,
});
@override
String toString() {
return 'LogEntry(timestamp: $timestamp, log: $log)';
}
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/persistence/favorite_device.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'favorite_device.dart';
class FavoriteDeviceMapper extends ClassMapperBase<FavoriteDevice> {
FavoriteDeviceMapper._();
static FavoriteDeviceMapper? _instance;
static FavoriteDeviceMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = FavoriteDeviceMapper._());
}
return _instance!;
}
@override
final String id = 'FavoriteDevice';
static String _$id(FavoriteDevice v) => v.id;
static const Field<FavoriteDevice, String> _f$id = Field('id', _$id);
static String _$fingerprint(FavoriteDevice v) => v.fingerprint;
static const Field<FavoriteDevice, String> _f$fingerprint = Field('fingerprint', _$fingerprint);
static String _$ip(FavoriteDevice v) => v.ip;
static const Field<FavoriteDevice, String> _f$ip = Field('ip', _$ip);
static int _$port(FavoriteDevice v) => v.port;
static const Field<FavoriteDevice, int> _f$port = Field('port', _$port);
static String _$alias(FavoriteDevice v) => v.alias;
static const Field<FavoriteDevice, String> _f$alias = Field('alias', _$alias);
static bool _$customAlias(FavoriteDevice v) => v.customAlias;
static const Field<FavoriteDevice, bool> _f$customAlias = Field('customAlias', _$customAlias, opt: true, def: false);
@override
final MappableFields<FavoriteDevice> fields = const {
#id: _f$id,
#fingerprint: _f$fingerprint,
#ip: _f$ip,
#port: _f$port,
#alias: _f$alias,
#customAlias: _f$customAlias,
};
static FavoriteDevice _instantiate(DecodingData data) {
return FavoriteDevice(
id: data.dec(_f$id),
fingerprint: data.dec(_f$fingerprint),
ip: data.dec(_f$ip),
port: data.dec(_f$port),
alias: data.dec(_f$alias),
customAlias: data.dec(_f$customAlias));
}
@override
final Function instantiate = _instantiate;
static FavoriteDevice fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<FavoriteDevice>(map);
}
static FavoriteDevice deserialize(String json) {
return ensureInitialized().decodeJson<FavoriteDevice>(json);
}
}
mixin FavoriteDeviceMappable {
String serialize() {
return FavoriteDeviceMapper.ensureInitialized().encodeJson<FavoriteDevice>(this as FavoriteDevice);
}
Map<String, dynamic> toJson() {
return FavoriteDeviceMapper.ensureInitialized().encodeMap<FavoriteDevice>(this as FavoriteDevice);
}
FavoriteDeviceCopyWith<FavoriteDevice, FavoriteDevice, FavoriteDevice> get copyWith =>
_FavoriteDeviceCopyWithImpl(this as FavoriteDevice, $identity, $identity);
@override
String toString() {
return FavoriteDeviceMapper.ensureInitialized().stringifyValue(this as FavoriteDevice);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && FavoriteDeviceMapper.ensureInitialized().isValueEqual(this as FavoriteDevice, other));
}
@override
int get hashCode {
return FavoriteDeviceMapper.ensureInitialized().hashValue(this as FavoriteDevice);
}
}
extension FavoriteDeviceValueCopy<$R, $Out> on ObjectCopyWith<$R, FavoriteDevice, $Out> {
FavoriteDeviceCopyWith<$R, FavoriteDevice, $Out> get $asFavoriteDevice => $base.as((v, t, t2) => _FavoriteDeviceCopyWithImpl(v, t, t2));
}
abstract class FavoriteDeviceCopyWith<$R, $In extends FavoriteDevice, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call({String? id, String? fingerprint, String? ip, int? port, String? alias, bool? customAlias});
FavoriteDeviceCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _FavoriteDeviceCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, FavoriteDevice, $Out>
implements FavoriteDeviceCopyWith<$R, FavoriteDevice, $Out> {
_FavoriteDeviceCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<FavoriteDevice> $mapper = FavoriteDeviceMapper.ensureInitialized();
@override
$R call({String? id, String? fingerprint, String? ip, int? port, String? alias, bool? customAlias}) => $apply(FieldCopyWithData({
if (id != null) #id: id,
if (fingerprint != null) #fingerprint: fingerprint,
if (ip != null) #ip: ip,
if (port != null) #port: port,
if (alias != null) #alias: alias,
if (customAlias != null) #customAlias: customAlias
}));
@override
FavoriteDevice $make(CopyWithData data) => FavoriteDevice(
id: data.get(#id, or: $value.id),
fingerprint: data.get(#fingerprint, or: $value.fingerprint),
ip: data.get(#ip, or: $value.ip),
port: data.get(#port, or: $value.port),
alias: data.get(#alias, or: $value.alias),
customAlias: data.get(#customAlias, or: $value.customAlias));
@override
FavoriteDeviceCopyWith<$R2, FavoriteDevice, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _FavoriteDeviceCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/persistence/favorite_device.dart | import 'package:dart_mappable/dart_mappable.dart';
import 'package:uuid/uuid.dart';
part 'favorite_device.mapper.dart';
const _uuid = Uuid();
@MappableClass()
class FavoriteDevice with FavoriteDeviceMappable {
final String id;
final String fingerprint;
final String ip;
final int port;
final String alias;
/// If true, the alias was set by the user.
/// If false, the alias is derived from the original device alias and
/// should be updated when the original device alias changes.
final bool customAlias;
const FavoriteDevice({
required this.id,
required this.fingerprint,
required this.ip,
required this.port,
required this.alias,
this.customAlias = false,
});
factory FavoriteDevice.fromValues({
required String fingerprint,
required String ip,
required int port,
required String alias,
}) {
return FavoriteDevice(
id: _uuid.v1(),
fingerprint: fingerprint,
ip: ip,
port: port,
alias: alias,
customAlias: false,
);
}
static const fromJson = FavoriteDeviceMapper.fromJson;
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/persistence/receive_history_entry.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:intl/intl.dart';
import 'package:localsend_app/gen/strings.g.dart';
part 'receive_history_entry.mapper.dart';
@MappableClass()
class ReceiveHistoryEntry with ReceiveHistoryEntryMappable {
final String id;
final String fileName;
final FileType fileType;
final String? path;
final bool savedToGallery;
final int fileSize;
final String senderAlias;
final DateTime timestamp;
const ReceiveHistoryEntry({
required this.id,
required this.fileName,
required this.fileType,
required this.path,
required this.savedToGallery,
required this.fileSize,
required this.senderAlias,
required this.timestamp,
});
/// Format string using the intl package.
/// Because the raw timestamp is saved in UTC, we need to transform it to local time zone first.
String get timestampString {
final localTimestamp = timestamp.toLocal();
return '${DateFormat.yMd(LocaleSettings.currentLocale.languageTag).format(localTimestamp)} ${DateFormat.jm(LocaleSettings.currentLocale.languageTag).format(localTimestamp)}';
}
static const fromJson = ReceiveHistoryEntryMapper.fromJson;
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/persistence/color_mode.dart | enum ColorMode {
system, // dynamic colors
localsend,
oled,
yaru,
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/persistence/receive_history_entry.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'receive_history_entry.dart';
class ReceiveHistoryEntryMapper extends ClassMapperBase<ReceiveHistoryEntry> {
ReceiveHistoryEntryMapper._();
static ReceiveHistoryEntryMapper? _instance;
static ReceiveHistoryEntryMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = ReceiveHistoryEntryMapper._());
FileTypeMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'ReceiveHistoryEntry';
static String _$id(ReceiveHistoryEntry v) => v.id;
static const Field<ReceiveHistoryEntry, String> _f$id = Field('id', _$id);
static String _$fileName(ReceiveHistoryEntry v) => v.fileName;
static const Field<ReceiveHistoryEntry, String> _f$fileName = Field('fileName', _$fileName);
static FileType _$fileType(ReceiveHistoryEntry v) => v.fileType;
static const Field<ReceiveHistoryEntry, FileType> _f$fileType = Field('fileType', _$fileType);
static String? _$path(ReceiveHistoryEntry v) => v.path;
static const Field<ReceiveHistoryEntry, String> _f$path = Field('path', _$path);
static bool _$savedToGallery(ReceiveHistoryEntry v) => v.savedToGallery;
static const Field<ReceiveHistoryEntry, bool> _f$savedToGallery = Field('savedToGallery', _$savedToGallery);
static int _$fileSize(ReceiveHistoryEntry v) => v.fileSize;
static const Field<ReceiveHistoryEntry, int> _f$fileSize = Field('fileSize', _$fileSize);
static String _$senderAlias(ReceiveHistoryEntry v) => v.senderAlias;
static const Field<ReceiveHistoryEntry, String> _f$senderAlias = Field('senderAlias', _$senderAlias);
static DateTime _$timestamp(ReceiveHistoryEntry v) => v.timestamp;
static const Field<ReceiveHistoryEntry, DateTime> _f$timestamp = Field('timestamp', _$timestamp);
@override
final MappableFields<ReceiveHistoryEntry> fields = const {
#id: _f$id,
#fileName: _f$fileName,
#fileType: _f$fileType,
#path: _f$path,
#savedToGallery: _f$savedToGallery,
#fileSize: _f$fileSize,
#senderAlias: _f$senderAlias,
#timestamp: _f$timestamp,
};
static ReceiveHistoryEntry _instantiate(DecodingData data) {
return ReceiveHistoryEntry(
id: data.dec(_f$id),
fileName: data.dec(_f$fileName),
fileType: data.dec(_f$fileType),
path: data.dec(_f$path),
savedToGallery: data.dec(_f$savedToGallery),
fileSize: data.dec(_f$fileSize),
senderAlias: data.dec(_f$senderAlias),
timestamp: data.dec(_f$timestamp));
}
@override
final Function instantiate = _instantiate;
static ReceiveHistoryEntry fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<ReceiveHistoryEntry>(map);
}
static ReceiveHistoryEntry deserialize(String json) {
return ensureInitialized().decodeJson<ReceiveHistoryEntry>(json);
}
}
mixin ReceiveHistoryEntryMappable {
String serialize() {
return ReceiveHistoryEntryMapper.ensureInitialized().encodeJson<ReceiveHistoryEntry>(this as ReceiveHistoryEntry);
}
Map<String, dynamic> toJson() {
return ReceiveHistoryEntryMapper.ensureInitialized().encodeMap<ReceiveHistoryEntry>(this as ReceiveHistoryEntry);
}
ReceiveHistoryEntryCopyWith<ReceiveHistoryEntry, ReceiveHistoryEntry, ReceiveHistoryEntry> get copyWith =>
_ReceiveHistoryEntryCopyWithImpl(this as ReceiveHistoryEntry, $identity, $identity);
@override
String toString() {
return ReceiveHistoryEntryMapper.ensureInitialized().stringifyValue(this as ReceiveHistoryEntry);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && ReceiveHistoryEntryMapper.ensureInitialized().isValueEqual(this as ReceiveHistoryEntry, other));
}
@override
int get hashCode {
return ReceiveHistoryEntryMapper.ensureInitialized().hashValue(this as ReceiveHistoryEntry);
}
}
extension ReceiveHistoryEntryValueCopy<$R, $Out> on ObjectCopyWith<$R, ReceiveHistoryEntry, $Out> {
ReceiveHistoryEntryCopyWith<$R, ReceiveHistoryEntry, $Out> get $asReceiveHistoryEntry =>
$base.as((v, t, t2) => _ReceiveHistoryEntryCopyWithImpl(v, t, t2));
}
abstract class ReceiveHistoryEntryCopyWith<$R, $In extends ReceiveHistoryEntry, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call(
{String? id,
String? fileName,
FileType? fileType,
String? path,
bool? savedToGallery,
int? fileSize,
String? senderAlias,
DateTime? timestamp});
ReceiveHistoryEntryCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _ReceiveHistoryEntryCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, ReceiveHistoryEntry, $Out>
implements ReceiveHistoryEntryCopyWith<$R, ReceiveHistoryEntry, $Out> {
_ReceiveHistoryEntryCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<ReceiveHistoryEntry> $mapper = ReceiveHistoryEntryMapper.ensureInitialized();
@override
$R call(
{String? id,
String? fileName,
FileType? fileType,
Object? path = $none,
bool? savedToGallery,
int? fileSize,
String? senderAlias,
DateTime? timestamp}) =>
$apply(FieldCopyWithData({
if (id != null) #id: id,
if (fileName != null) #fileName: fileName,
if (fileType != null) #fileType: fileType,
if (path != $none) #path: path,
if (savedToGallery != null) #savedToGallery: savedToGallery,
if (fileSize != null) #fileSize: fileSize,
if (senderAlias != null) #senderAlias: senderAlias,
if (timestamp != null) #timestamp: timestamp
}));
@override
ReceiveHistoryEntry $make(CopyWithData data) => ReceiveHistoryEntry(
id: data.get(#id, or: $value.id),
fileName: data.get(#fileName, or: $value.fileName),
fileType: data.get(#fileType, or: $value.fileType),
path: data.get(#path, or: $value.path),
savedToGallery: data.get(#savedToGallery, or: $value.savedToGallery),
fileSize: data.get(#fileSize, or: $value.fileSize),
senderAlias: data.get(#senderAlias, or: $value.senderAlias),
timestamp: data.get(#timestamp, or: $value.timestamp));
@override
ReceiveHistoryEntryCopyWith<$R2, ReceiveHistoryEntry, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_ReceiveHistoryEntryCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/network_state.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'network_state.mapper.dart';
@MappableClass()
class NetworkState with NetworkStateMappable {
final List<String> localIps;
final bool initialized;
const NetworkState({
required this.localIps,
required this.initialized,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/settings_state.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/persistence/color_mode.dart';
import 'package:localsend_app/model/send_mode.dart';
part 'settings_state.mapper.dart';
@MappableClass()
class SettingsState with SettingsStateMappable {
final String showToken; // the token to show / maximize the window because only one instance is allowed
final String alias;
final ThemeMode theme;
final ColorMode colorMode;
final AppLocale? locale;
final int port;
final String multicastGroup;
final String? destination; // null = default
final bool saveToGallery; // only Android, iOS
final bool saveToHistory;
final bool quickSave; // automatically accept file requests
final bool autoFinish; // automatically finish sessions
final bool minimizeToTray; // minimize to tray instead of exiting the app
final bool launchAtStartup; // Tracks if the option is enabled on Linux
final bool autoStartLaunchMinimized; // start hidden in tray (only available when launchAtStartup is true)
final bool https;
final SendMode sendMode;
final bool saveWindowPlacement;
final bool enableAnimations;
final DeviceType? deviceType;
final String? deviceModel;
final bool shareViaLinkAutoAccept;
const SettingsState({
required this.showToken,
required this.alias,
required this.theme,
required this.colorMode,
required this.locale,
required this.port,
required this.multicastGroup,
required this.destination,
required this.saveToGallery,
required this.saveToHistory,
required this.quickSave,
required this.autoFinish,
required this.minimizeToTray,
required this.launchAtStartup,
required this.autoStartLaunchMinimized,
required this.https,
required this.sendMode,
required this.saveWindowPlacement,
required this.enableAnimations,
required this.deviceType,
required this.deviceModel,
required this.shareViaLinkAutoAccept,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/purchase_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'purchase_state.dart';
class PurchaseStateMapper extends ClassMapperBase<PurchaseState> {
PurchaseStateMapper._();
static PurchaseStateMapper? _instance;
static PurchaseStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = PurchaseStateMapper._());
}
return _instance!;
}
@override
final String id = 'PurchaseState';
static Map<PurchaseItem, String> _$prices(PurchaseState v) => v.prices;
static const Field<PurchaseState, Map<PurchaseItem, String>> _f$prices = Field('prices', _$prices);
static Set<PurchaseItem> _$purchases(PurchaseState v) => v.purchases;
static const Field<PurchaseState, Set<PurchaseItem>> _f$purchases = Field('purchases', _$purchases);
static bool _$pending(PurchaseState v) => v.pending;
static const Field<PurchaseState, bool> _f$pending = Field('pending', _$pending);
@override
final MappableFields<PurchaseState> fields = const {
#prices: _f$prices,
#purchases: _f$purchases,
#pending: _f$pending,
};
static PurchaseState _instantiate(DecodingData data) {
return PurchaseState(prices: data.dec(_f$prices), purchases: data.dec(_f$purchases), pending: data.dec(_f$pending));
}
@override
final Function instantiate = _instantiate;
static PurchaseState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<PurchaseState>(map);
}
static PurchaseState deserialize(String json) {
return ensureInitialized().decodeJson<PurchaseState>(json);
}
}
mixin PurchaseStateMappable {
String serialize() {
return PurchaseStateMapper.ensureInitialized().encodeJson<PurchaseState>(this as PurchaseState);
}
Map<String, dynamic> toJson() {
return PurchaseStateMapper.ensureInitialized().encodeMap<PurchaseState>(this as PurchaseState);
}
PurchaseStateCopyWith<PurchaseState, PurchaseState, PurchaseState> get copyWith =>
_PurchaseStateCopyWithImpl(this as PurchaseState, $identity, $identity);
@override
String toString() {
return PurchaseStateMapper.ensureInitialized().stringifyValue(this as PurchaseState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && PurchaseStateMapper.ensureInitialized().isValueEqual(this as PurchaseState, other));
}
@override
int get hashCode {
return PurchaseStateMapper.ensureInitialized().hashValue(this as PurchaseState);
}
}
extension PurchaseStateValueCopy<$R, $Out> on ObjectCopyWith<$R, PurchaseState, $Out> {
PurchaseStateCopyWith<$R, PurchaseState, $Out> get $asPurchaseState => $base.as((v, t, t2) => _PurchaseStateCopyWithImpl(v, t, t2));
}
abstract class PurchaseStateCopyWith<$R, $In extends PurchaseState, $Out> implements ClassCopyWith<$R, $In, $Out> {
MapCopyWith<$R, PurchaseItem, String, ObjectCopyWith<$R, String, String>> get prices;
$R call({Map<PurchaseItem, String>? prices, Set<PurchaseItem>? purchases, bool? pending});
PurchaseStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _PurchaseStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, PurchaseState, $Out>
implements PurchaseStateCopyWith<$R, PurchaseState, $Out> {
_PurchaseStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<PurchaseState> $mapper = PurchaseStateMapper.ensureInitialized();
@override
MapCopyWith<$R, PurchaseItem, String, ObjectCopyWith<$R, String, String>> get prices =>
MapCopyWith($value.prices, (v, t) => ObjectCopyWith(v, $identity, t), (v) => call(prices: v));
@override
$R call({Map<PurchaseItem, String>? prices, Set<PurchaseItem>? purchases, bool? pending}) => $apply(
FieldCopyWithData({if (prices != null) #prices: prices, if (purchases != null) #purchases: purchases, if (pending != null) #pending: pending}));
@override
PurchaseState $make(CopyWithData data) => PurchaseState(
prices: data.get(#prices, or: $value.prices),
purchases: data.get(#purchases, or: $value.purchases),
pending: data.get(#pending, or: $value.pending));
@override
PurchaseStateCopyWith<$R2, PurchaseState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _PurchaseStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/nearby_devices_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'nearby_devices_state.dart';
class NearbyDevicesStateMapper extends ClassMapperBase<NearbyDevicesState> {
NearbyDevicesStateMapper._();
static NearbyDevicesStateMapper? _instance;
static NearbyDevicesStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = NearbyDevicesStateMapper._());
DeviceMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'NearbyDevicesState';
static bool _$runningFavoriteScan(NearbyDevicesState v) => v.runningFavoriteScan;
static const Field<NearbyDevicesState, bool> _f$runningFavoriteScan = Field('runningFavoriteScan', _$runningFavoriteScan);
static Set<String> _$runningIps(NearbyDevicesState v) => v.runningIps;
static const Field<NearbyDevicesState, Set<String>> _f$runningIps = Field('runningIps', _$runningIps);
static Map<String, Device> _$devices(NearbyDevicesState v) => v.devices;
static const Field<NearbyDevicesState, Map<String, Device>> _f$devices = Field('devices', _$devices);
@override
final MappableFields<NearbyDevicesState> fields = const {
#runningFavoriteScan: _f$runningFavoriteScan,
#runningIps: _f$runningIps,
#devices: _f$devices,
};
static NearbyDevicesState _instantiate(DecodingData data) {
return NearbyDevicesState(
runningFavoriteScan: data.dec(_f$runningFavoriteScan), runningIps: data.dec(_f$runningIps), devices: data.dec(_f$devices));
}
@override
final Function instantiate = _instantiate;
static NearbyDevicesState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<NearbyDevicesState>(map);
}
static NearbyDevicesState deserialize(String json) {
return ensureInitialized().decodeJson<NearbyDevicesState>(json);
}
}
mixin NearbyDevicesStateMappable {
String serialize() {
return NearbyDevicesStateMapper.ensureInitialized().encodeJson<NearbyDevicesState>(this as NearbyDevicesState);
}
Map<String, dynamic> toJson() {
return NearbyDevicesStateMapper.ensureInitialized().encodeMap<NearbyDevicesState>(this as NearbyDevicesState);
}
NearbyDevicesStateCopyWith<NearbyDevicesState, NearbyDevicesState, NearbyDevicesState> get copyWith =>
_NearbyDevicesStateCopyWithImpl(this as NearbyDevicesState, $identity, $identity);
@override
String toString() {
return NearbyDevicesStateMapper.ensureInitialized().stringifyValue(this as NearbyDevicesState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && NearbyDevicesStateMapper.ensureInitialized().isValueEqual(this as NearbyDevicesState, other));
}
@override
int get hashCode {
return NearbyDevicesStateMapper.ensureInitialized().hashValue(this as NearbyDevicesState);
}
}
extension NearbyDevicesStateValueCopy<$R, $Out> on ObjectCopyWith<$R, NearbyDevicesState, $Out> {
NearbyDevicesStateCopyWith<$R, NearbyDevicesState, $Out> get $asNearbyDevicesState =>
$base.as((v, t, t2) => _NearbyDevicesStateCopyWithImpl(v, t, t2));
}
abstract class NearbyDevicesStateCopyWith<$R, $In extends NearbyDevicesState, $Out> implements ClassCopyWith<$R, $In, $Out> {
MapCopyWith<$R, String, Device, DeviceCopyWith<$R, Device, Device>> get devices;
$R call({bool? runningFavoriteScan, Set<String>? runningIps, Map<String, Device>? devices});
NearbyDevicesStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _NearbyDevicesStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, NearbyDevicesState, $Out>
implements NearbyDevicesStateCopyWith<$R, NearbyDevicesState, $Out> {
_NearbyDevicesStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<NearbyDevicesState> $mapper = NearbyDevicesStateMapper.ensureInitialized();
@override
MapCopyWith<$R, String, Device, DeviceCopyWith<$R, Device, Device>> get devices =>
MapCopyWith($value.devices, (v, t) => v.copyWith.$chain(t), (v) => call(devices: v));
@override
$R call({bool? runningFavoriteScan, Set<String>? runningIps, Map<String, Device>? devices}) => $apply(FieldCopyWithData({
if (runningFavoriteScan != null) #runningFavoriteScan: runningFavoriteScan,
if (runningIps != null) #runningIps: runningIps,
if (devices != null) #devices: devices
}));
@override
NearbyDevicesState $make(CopyWithData data) => NearbyDevicesState(
runningFavoriteScan: data.get(#runningFavoriteScan, or: $value.runningFavoriteScan),
runningIps: data.get(#runningIps, or: $value.runningIps),
devices: data.get(#devices, or: $value.devices));
@override
NearbyDevicesStateCopyWith<$R2, NearbyDevicesState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_NearbyDevicesStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/purchase_state.dart | import 'package:dart_mappable/dart_mappable.dart';
import 'package:flutter/foundation.dart';
part 'purchase_state.mapper.dart';
enum PurchaseItem {
donate5(
androidId: 'localsend_android_donate_5',
iosId: 'localsend_ios_donate_5',
),
donate10(
androidId: 'localsend_android_donate_10',
iosId: 'localsend_ios_donate_10',
),
donate20(
androidId: 'localsend_android_donate_20',
iosId: 'localsend_ios_donate_20',
),
donate50(
androidId: 'localsend_android_donate_50',
iosId: 'localsend_ios_donate_50',
);
const PurchaseItem({
required this.androidId,
required this.iosId,
});
final String androidId;
final String iosId;
String get platformProductId => defaultTargetPlatform == TargetPlatform.android ? androidId : iosId;
}
@MappableClass()
class PurchaseState with PurchaseStateMappable {
final Map<PurchaseItem, String> prices;
final Set<PurchaseItem> purchases;
final bool pending;
const PurchaseState({
required this.prices,
required this.purchases,
required this.pending,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/settings_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'settings_state.dart';
class SettingsStateMapper extends ClassMapperBase<SettingsState> {
SettingsStateMapper._();
static SettingsStateMapper? _instance;
static SettingsStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = SettingsStateMapper._());
DeviceTypeMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'SettingsState';
static String _$showToken(SettingsState v) => v.showToken;
static const Field<SettingsState, String> _f$showToken = Field('showToken', _$showToken);
static String _$alias(SettingsState v) => v.alias;
static const Field<SettingsState, String> _f$alias = Field('alias', _$alias);
static ThemeMode _$theme(SettingsState v) => v.theme;
static const Field<SettingsState, ThemeMode> _f$theme = Field('theme', _$theme);
static ColorMode _$colorMode(SettingsState v) => v.colorMode;
static const Field<SettingsState, ColorMode> _f$colorMode = Field('colorMode', _$colorMode);
static AppLocale? _$locale(SettingsState v) => v.locale;
static const Field<SettingsState, AppLocale> _f$locale = Field('locale', _$locale);
static int _$port(SettingsState v) => v.port;
static const Field<SettingsState, int> _f$port = Field('port', _$port);
static String _$multicastGroup(SettingsState v) => v.multicastGroup;
static const Field<SettingsState, String> _f$multicastGroup = Field('multicastGroup', _$multicastGroup);
static String? _$destination(SettingsState v) => v.destination;
static const Field<SettingsState, String> _f$destination = Field('destination', _$destination);
static bool _$saveToGallery(SettingsState v) => v.saveToGallery;
static const Field<SettingsState, bool> _f$saveToGallery = Field('saveToGallery', _$saveToGallery);
static bool _$saveToHistory(SettingsState v) => v.saveToHistory;
static const Field<SettingsState, bool> _f$saveToHistory = Field('saveToHistory', _$saveToHistory);
static bool _$quickSave(SettingsState v) => v.quickSave;
static const Field<SettingsState, bool> _f$quickSave = Field('quickSave', _$quickSave);
static bool _$autoFinish(SettingsState v) => v.autoFinish;
static const Field<SettingsState, bool> _f$autoFinish = Field('autoFinish', _$autoFinish);
static bool _$minimizeToTray(SettingsState v) => v.minimizeToTray;
static const Field<SettingsState, bool> _f$minimizeToTray = Field('minimizeToTray', _$minimizeToTray);
static bool _$launchAtStartup(SettingsState v) => v.launchAtStartup;
static const Field<SettingsState, bool> _f$launchAtStartup = Field('launchAtStartup', _$launchAtStartup);
static bool _$autoStartLaunchMinimized(SettingsState v) => v.autoStartLaunchMinimized;
static const Field<SettingsState, bool> _f$autoStartLaunchMinimized = Field('autoStartLaunchMinimized', _$autoStartLaunchMinimized);
static bool _$https(SettingsState v) => v.https;
static const Field<SettingsState, bool> _f$https = Field('https', _$https);
static SendMode _$sendMode(SettingsState v) => v.sendMode;
static const Field<SettingsState, SendMode> _f$sendMode = Field('sendMode', _$sendMode);
static bool _$saveWindowPlacement(SettingsState v) => v.saveWindowPlacement;
static const Field<SettingsState, bool> _f$saveWindowPlacement = Field('saveWindowPlacement', _$saveWindowPlacement);
static bool _$enableAnimations(SettingsState v) => v.enableAnimations;
static const Field<SettingsState, bool> _f$enableAnimations = Field('enableAnimations', _$enableAnimations);
static DeviceType? _$deviceType(SettingsState v) => v.deviceType;
static const Field<SettingsState, DeviceType> _f$deviceType = Field('deviceType', _$deviceType);
static String? _$deviceModel(SettingsState v) => v.deviceModel;
static const Field<SettingsState, String> _f$deviceModel = Field('deviceModel', _$deviceModel);
static bool _$shareViaLinkAutoAccept(SettingsState v) => v.shareViaLinkAutoAccept;
static const Field<SettingsState, bool> _f$shareViaLinkAutoAccept = Field('shareViaLinkAutoAccept', _$shareViaLinkAutoAccept);
@override
final MappableFields<SettingsState> fields = const {
#showToken: _f$showToken,
#alias: _f$alias,
#theme: _f$theme,
#colorMode: _f$colorMode,
#locale: _f$locale,
#port: _f$port,
#multicastGroup: _f$multicastGroup,
#destination: _f$destination,
#saveToGallery: _f$saveToGallery,
#saveToHistory: _f$saveToHistory,
#quickSave: _f$quickSave,
#autoFinish: _f$autoFinish,
#minimizeToTray: _f$minimizeToTray,
#launchAtStartup: _f$launchAtStartup,
#autoStartLaunchMinimized: _f$autoStartLaunchMinimized,
#https: _f$https,
#sendMode: _f$sendMode,
#saveWindowPlacement: _f$saveWindowPlacement,
#enableAnimations: _f$enableAnimations,
#deviceType: _f$deviceType,
#deviceModel: _f$deviceModel,
#shareViaLinkAutoAccept: _f$shareViaLinkAutoAccept,
};
static SettingsState _instantiate(DecodingData data) {
return SettingsState(
showToken: data.dec(_f$showToken),
alias: data.dec(_f$alias),
theme: data.dec(_f$theme),
colorMode: data.dec(_f$colorMode),
locale: data.dec(_f$locale),
port: data.dec(_f$port),
multicastGroup: data.dec(_f$multicastGroup),
destination: data.dec(_f$destination),
saveToGallery: data.dec(_f$saveToGallery),
saveToHistory: data.dec(_f$saveToHistory),
quickSave: data.dec(_f$quickSave),
autoFinish: data.dec(_f$autoFinish),
minimizeToTray: data.dec(_f$minimizeToTray),
launchAtStartup: data.dec(_f$launchAtStartup),
autoStartLaunchMinimized: data.dec(_f$autoStartLaunchMinimized),
https: data.dec(_f$https),
sendMode: data.dec(_f$sendMode),
saveWindowPlacement: data.dec(_f$saveWindowPlacement),
enableAnimations: data.dec(_f$enableAnimations),
deviceType: data.dec(_f$deviceType),
deviceModel: data.dec(_f$deviceModel),
shareViaLinkAutoAccept: data.dec(_f$shareViaLinkAutoAccept));
}
@override
final Function instantiate = _instantiate;
static SettingsState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<SettingsState>(map);
}
static SettingsState deserialize(String json) {
return ensureInitialized().decodeJson<SettingsState>(json);
}
}
mixin SettingsStateMappable {
String serialize() {
return SettingsStateMapper.ensureInitialized().encodeJson<SettingsState>(this as SettingsState);
}
Map<String, dynamic> toJson() {
return SettingsStateMapper.ensureInitialized().encodeMap<SettingsState>(this as SettingsState);
}
SettingsStateCopyWith<SettingsState, SettingsState, SettingsState> get copyWith =>
_SettingsStateCopyWithImpl(this as SettingsState, $identity, $identity);
@override
String toString() {
return SettingsStateMapper.ensureInitialized().stringifyValue(this as SettingsState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && SettingsStateMapper.ensureInitialized().isValueEqual(this as SettingsState, other));
}
@override
int get hashCode {
return SettingsStateMapper.ensureInitialized().hashValue(this as SettingsState);
}
}
extension SettingsStateValueCopy<$R, $Out> on ObjectCopyWith<$R, SettingsState, $Out> {
SettingsStateCopyWith<$R, SettingsState, $Out> get $asSettingsState => $base.as((v, t, t2) => _SettingsStateCopyWithImpl(v, t, t2));
}
abstract class SettingsStateCopyWith<$R, $In extends SettingsState, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call(
{String? showToken,
String? alias,
ThemeMode? theme,
ColorMode? colorMode,
AppLocale? locale,
int? port,
String? multicastGroup,
String? destination,
bool? saveToGallery,
bool? saveToHistory,
bool? quickSave,
bool? autoFinish,
bool? minimizeToTray,
bool? launchAtStartup,
bool? autoStartLaunchMinimized,
bool? https,
SendMode? sendMode,
bool? saveWindowPlacement,
bool? enableAnimations,
DeviceType? deviceType,
String? deviceModel,
bool? shareViaLinkAutoAccept});
SettingsStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _SettingsStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, SettingsState, $Out>
implements SettingsStateCopyWith<$R, SettingsState, $Out> {
_SettingsStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<SettingsState> $mapper = SettingsStateMapper.ensureInitialized();
@override
$R call(
{String? showToken,
String? alias,
ThemeMode? theme,
ColorMode? colorMode,
Object? locale = $none,
int? port,
String? multicastGroup,
Object? destination = $none,
bool? saveToGallery,
bool? saveToHistory,
bool? quickSave,
bool? autoFinish,
bool? minimizeToTray,
bool? launchAtStartup,
bool? autoStartLaunchMinimized,
bool? https,
SendMode? sendMode,
bool? saveWindowPlacement,
bool? enableAnimations,
Object? deviceType = $none,
Object? deviceModel = $none,
bool? shareViaLinkAutoAccept}) =>
$apply(FieldCopyWithData({
if (showToken != null) #showToken: showToken,
if (alias != null) #alias: alias,
if (theme != null) #theme: theme,
if (colorMode != null) #colorMode: colorMode,
if (locale != $none) #locale: locale,
if (port != null) #port: port,
if (multicastGroup != null) #multicastGroup: multicastGroup,
if (destination != $none) #destination: destination,
if (saveToGallery != null) #saveToGallery: saveToGallery,
if (saveToHistory != null) #saveToHistory: saveToHistory,
if (quickSave != null) #quickSave: quickSave,
if (autoFinish != null) #autoFinish: autoFinish,
if (minimizeToTray != null) #minimizeToTray: minimizeToTray,
if (launchAtStartup != null) #launchAtStartup: launchAtStartup,
if (autoStartLaunchMinimized != null) #autoStartLaunchMinimized: autoStartLaunchMinimized,
if (https != null) #https: https,
if (sendMode != null) #sendMode: sendMode,
if (saveWindowPlacement != null) #saveWindowPlacement: saveWindowPlacement,
if (enableAnimations != null) #enableAnimations: enableAnimations,
if (deviceType != $none) #deviceType: deviceType,
if (deviceModel != $none) #deviceModel: deviceModel,
if (shareViaLinkAutoAccept != null) #shareViaLinkAutoAccept: shareViaLinkAutoAccept
}));
@override
SettingsState $make(CopyWithData data) => SettingsState(
showToken: data.get(#showToken, or: $value.showToken),
alias: data.get(#alias, or: $value.alias),
theme: data.get(#theme, or: $value.theme),
colorMode: data.get(#colorMode, or: $value.colorMode),
locale: data.get(#locale, or: $value.locale),
port: data.get(#port, or: $value.port),
multicastGroup: data.get(#multicastGroup, or: $value.multicastGroup),
destination: data.get(#destination, or: $value.destination),
saveToGallery: data.get(#saveToGallery, or: $value.saveToGallery),
saveToHistory: data.get(#saveToHistory, or: $value.saveToHistory),
quickSave: data.get(#quickSave, or: $value.quickSave),
autoFinish: data.get(#autoFinish, or: $value.autoFinish),
minimizeToTray: data.get(#minimizeToTray, or: $value.minimizeToTray),
launchAtStartup: data.get(#launchAtStartup, or: $value.launchAtStartup),
autoStartLaunchMinimized: data.get(#autoStartLaunchMinimized, or: $value.autoStartLaunchMinimized),
https: data.get(#https, or: $value.https),
sendMode: data.get(#sendMode, or: $value.sendMode),
saveWindowPlacement: data.get(#saveWindowPlacement, or: $value.saveWindowPlacement),
enableAnimations: data.get(#enableAnimations, or: $value.enableAnimations),
deviceType: data.get(#deviceType, or: $value.deviceType),
deviceModel: data.get(#deviceModel, or: $value.deviceModel),
shareViaLinkAutoAccept: data.get(#shareViaLinkAutoAccept, or: $value.shareViaLinkAutoAccept));
@override
SettingsStateCopyWith<$R2, SettingsState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _SettingsStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/nearby_devices_state.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'nearby_devices_state.mapper.dart';
@MappableClass()
class NearbyDevicesState with NearbyDevicesStateMappable {
final bool runningFavoriteScan;
final Set<String> runningIps; // list of local ips
final Map<String, Device> devices; // ip -> device
const NearbyDevicesState({
required this.runningFavoriteScan,
required this.runningIps,
required this.devices,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model | mirrored_repositories/localsend/app/lib/model/state/network_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'network_state.dart';
class NetworkStateMapper extends ClassMapperBase<NetworkState> {
NetworkStateMapper._();
static NetworkStateMapper? _instance;
static NetworkStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = NetworkStateMapper._());
}
return _instance!;
}
@override
final String id = 'NetworkState';
static List<String> _$localIps(NetworkState v) => v.localIps;
static const Field<NetworkState, List<String>> _f$localIps = Field('localIps', _$localIps);
static bool _$initialized(NetworkState v) => v.initialized;
static const Field<NetworkState, bool> _f$initialized = Field('initialized', _$initialized);
@override
final MappableFields<NetworkState> fields = const {
#localIps: _f$localIps,
#initialized: _f$initialized,
};
static NetworkState _instantiate(DecodingData data) {
return NetworkState(localIps: data.dec(_f$localIps), initialized: data.dec(_f$initialized));
}
@override
final Function instantiate = _instantiate;
static NetworkState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<NetworkState>(map);
}
static NetworkState deserialize(String json) {
return ensureInitialized().decodeJson<NetworkState>(json);
}
}
mixin NetworkStateMappable {
String serialize() {
return NetworkStateMapper.ensureInitialized().encodeJson<NetworkState>(this as NetworkState);
}
Map<String, dynamic> toJson() {
return NetworkStateMapper.ensureInitialized().encodeMap<NetworkState>(this as NetworkState);
}
NetworkStateCopyWith<NetworkState, NetworkState, NetworkState> get copyWith =>
_NetworkStateCopyWithImpl(this as NetworkState, $identity, $identity);
@override
String toString() {
return NetworkStateMapper.ensureInitialized().stringifyValue(this as NetworkState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && NetworkStateMapper.ensureInitialized().isValueEqual(this as NetworkState, other));
}
@override
int get hashCode {
return NetworkStateMapper.ensureInitialized().hashValue(this as NetworkState);
}
}
extension NetworkStateValueCopy<$R, $Out> on ObjectCopyWith<$R, NetworkState, $Out> {
NetworkStateCopyWith<$R, NetworkState, $Out> get $asNetworkState => $base.as((v, t, t2) => _NetworkStateCopyWithImpl(v, t, t2));
}
abstract class NetworkStateCopyWith<$R, $In extends NetworkState, $Out> implements ClassCopyWith<$R, $In, $Out> {
ListCopyWith<$R, String, ObjectCopyWith<$R, String, String>> get localIps;
$R call({List<String>? localIps, bool? initialized});
NetworkStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _NetworkStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, NetworkState, $Out> implements NetworkStateCopyWith<$R, NetworkState, $Out> {
_NetworkStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<NetworkState> $mapper = NetworkStateMapper.ensureInitialized();
@override
ListCopyWith<$R, String, ObjectCopyWith<$R, String, String>> get localIps =>
ListCopyWith($value.localIps, (v, t) => ObjectCopyWith(v, $identity, t), (v) => call(localIps: v));
@override
$R call({List<String>? localIps, bool? initialized}) =>
$apply(FieldCopyWithData({if (localIps != null) #localIps: localIps, if (initialized != null) #initialized: initialized}));
@override
NetworkState $make(CopyWithData data) =>
NetworkState(localIps: data.get(#localIps, or: $value.localIps), initialized: data.get(#initialized, or: $value.initialized));
@override
NetworkStateCopyWith<$R2, NetworkState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _NetworkStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/send/send_session_state.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:dio/dio.dart';
import 'package:localsend_app/model/state/send/sending_file.dart';
part 'send_session_state.mapper.dart';
@MappableClass()
class SendSessionState with SendSessionStateMappable {
final String sessionId;
final String? remoteSessionId; // v2
final bool background;
final SessionStatus status;
final Device target;
final Map<String, SendingFile> files; // file id as key
final int? startTime;
final int? endTime;
final CancelToken? cancelToken;
final String? errorMessage;
const SendSessionState({
required this.sessionId,
required this.remoteSessionId,
required this.background,
required this.status,
required this.target,
required this.files,
required this.startTime,
required this.endTime,
required this.cancelToken,
required this.errorMessage,
});
/// Custom toString() to avoid printing the bytes.
/// The default toString() does not respect the overridden toString() of
/// SendingFile.
@override
String toString() {
return 'SendSessionState(sessionId: $sessionId, remoteSessionId: $remoteSessionId, background: $background, status: $status, target: $target, files: $files, startTime: $startTime, endTime: $endTime, cancelToken: $cancelToken, errorMessage: $errorMessage)';
}
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/send/sending_file.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'sending_file.dart';
class SendingFileMapper extends ClassMapperBase<SendingFile> {
SendingFileMapper._();
static SendingFileMapper? _instance;
static SendingFileMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = SendingFileMapper._());
}
return _instance!;
}
@override
final String id = 'SendingFile';
static FileDto _$file(SendingFile v) => v.file;
static const Field<SendingFile, FileDto> _f$file = Field('file', _$file);
static FileStatus _$status(SendingFile v) => v.status;
static const Field<SendingFile, FileStatus> _f$status = Field('status', _$status);
static String? _$token(SendingFile v) => v.token;
static const Field<SendingFile, String> _f$token = Field('token', _$token);
static Uint8List? _$thumbnail(SendingFile v) => v.thumbnail;
static const Field<SendingFile, Uint8List> _f$thumbnail = Field('thumbnail', _$thumbnail);
static AssetEntity? _$asset(SendingFile v) => v.asset;
static const Field<SendingFile, AssetEntity> _f$asset = Field('asset', _$asset);
static String? _$path(SendingFile v) => v.path;
static const Field<SendingFile, String> _f$path = Field('path', _$path);
static List<int>? _$bytes(SendingFile v) => v.bytes;
static const Field<SendingFile, List<int>> _f$bytes = Field('bytes', _$bytes);
static String? _$errorMessage(SendingFile v) => v.errorMessage;
static const Field<SendingFile, String> _f$errorMessage = Field('errorMessage', _$errorMessage);
@override
final MappableFields<SendingFile> fields = const {
#file: _f$file,
#status: _f$status,
#token: _f$token,
#thumbnail: _f$thumbnail,
#asset: _f$asset,
#path: _f$path,
#bytes: _f$bytes,
#errorMessage: _f$errorMessage,
};
static SendingFile _instantiate(DecodingData data) {
return SendingFile(
file: data.dec(_f$file),
status: data.dec(_f$status),
token: data.dec(_f$token),
thumbnail: data.dec(_f$thumbnail),
asset: data.dec(_f$asset),
path: data.dec(_f$path),
bytes: data.dec(_f$bytes),
errorMessage: data.dec(_f$errorMessage));
}
@override
final Function instantiate = _instantiate;
static SendingFile fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<SendingFile>(map);
}
static SendingFile deserialize(String json) {
return ensureInitialized().decodeJson<SendingFile>(json);
}
}
mixin SendingFileMappable {
String serialize() {
return SendingFileMapper.ensureInitialized().encodeJson<SendingFile>(this as SendingFile);
}
Map<String, dynamic> toJson() {
return SendingFileMapper.ensureInitialized().encodeMap<SendingFile>(this as SendingFile);
}
SendingFileCopyWith<SendingFile, SendingFile, SendingFile> get copyWith => _SendingFileCopyWithImpl(this as SendingFile, $identity, $identity);
@override
String toString() {
return SendingFileMapper.ensureInitialized().stringifyValue(this as SendingFile);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && SendingFileMapper.ensureInitialized().isValueEqual(this as SendingFile, other));
}
@override
int get hashCode {
return SendingFileMapper.ensureInitialized().hashValue(this as SendingFile);
}
}
extension SendingFileValueCopy<$R, $Out> on ObjectCopyWith<$R, SendingFile, $Out> {
SendingFileCopyWith<$R, SendingFile, $Out> get $asSendingFile => $base.as((v, t, t2) => _SendingFileCopyWithImpl(v, t, t2));
}
abstract class SendingFileCopyWith<$R, $In extends SendingFile, $Out> implements ClassCopyWith<$R, $In, $Out> {
ListCopyWith<$R, int, ObjectCopyWith<$R, int, int>>? get bytes;
$R call(
{FileDto? file,
FileStatus? status,
String? token,
Uint8List? thumbnail,
AssetEntity? asset,
String? path,
List<int>? bytes,
String? errorMessage});
SendingFileCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _SendingFileCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, SendingFile, $Out> implements SendingFileCopyWith<$R, SendingFile, $Out> {
_SendingFileCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<SendingFile> $mapper = SendingFileMapper.ensureInitialized();
@override
ListCopyWith<$R, int, ObjectCopyWith<$R, int, int>>? get bytes =>
$value.bytes != null ? ListCopyWith($value.bytes!, (v, t) => ObjectCopyWith(v, $identity, t), (v) => call(bytes: v)) : null;
@override
$R call(
{FileDto? file,
FileStatus? status,
Object? token = $none,
Object? thumbnail = $none,
Object? asset = $none,
Object? path = $none,
Object? bytes = $none,
Object? errorMessage = $none}) =>
$apply(FieldCopyWithData({
if (file != null) #file: file,
if (status != null) #status: status,
if (token != $none) #token: token,
if (thumbnail != $none) #thumbnail: thumbnail,
if (asset != $none) #asset: asset,
if (path != $none) #path: path,
if (bytes != $none) #bytes: bytes,
if (errorMessage != $none) #errorMessage: errorMessage
}));
@override
SendingFile $make(CopyWithData data) => SendingFile(
file: data.get(#file, or: $value.file),
status: data.get(#status, or: $value.status),
token: data.get(#token, or: $value.token),
thumbnail: data.get(#thumbnail, or: $value.thumbnail),
asset: data.get(#asset, or: $value.asset),
path: data.get(#path, or: $value.path),
bytes: data.get(#bytes, or: $value.bytes),
errorMessage: data.get(#errorMessage, or: $value.errorMessage));
@override
SendingFileCopyWith<$R2, SendingFile, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _SendingFileCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/send/sending_file.dart | import 'dart:typed_data';
import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
part 'sending_file.mapper.dart';
@MappableClass()
class SendingFile with SendingFileMappable {
final FileDto file;
final FileStatus status;
final String? token;
final Uint8List? thumbnail;
final AssetEntity? asset; // for thumbnails
final String? path; // android, iOS, desktop
final List<int>? bytes; // web
final String? errorMessage; // when status == failed
const SendingFile({
required this.file,
required this.status,
required this.token,
required this.thumbnail,
required this.asset,
required this.path,
required this.bytes,
required this.errorMessage,
});
/// Custom toString() to avoid printing the bytes.
@override
String toString() {
return 'SendingFile(file: $file, status: $status, token: $token, thumbnail: ${thumbnail != null ? thumbnail!.length : 'null'}, asset: $asset, path: $path, bytes: ${bytes != null ? bytes!.length : 'null'}, errorMessage: $errorMessage)';
}
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/send/send_session_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'send_session_state.dart';
class SendSessionStateMapper extends ClassMapperBase<SendSessionState> {
SendSessionStateMapper._();
static SendSessionStateMapper? _instance;
static SendSessionStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = SendSessionStateMapper._());
DeviceMapper.ensureInitialized();
SendingFileMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'SendSessionState';
static String _$sessionId(SendSessionState v) => v.sessionId;
static const Field<SendSessionState, String> _f$sessionId = Field('sessionId', _$sessionId);
static String? _$remoteSessionId(SendSessionState v) => v.remoteSessionId;
static const Field<SendSessionState, String> _f$remoteSessionId = Field('remoteSessionId', _$remoteSessionId);
static bool _$background(SendSessionState v) => v.background;
static const Field<SendSessionState, bool> _f$background = Field('background', _$background);
static SessionStatus _$status(SendSessionState v) => v.status;
static const Field<SendSessionState, SessionStatus> _f$status = Field('status', _$status);
static Device _$target(SendSessionState v) => v.target;
static const Field<SendSessionState, Device> _f$target = Field('target', _$target);
static Map<String, SendingFile> _$files(SendSessionState v) => v.files;
static const Field<SendSessionState, Map<String, SendingFile>> _f$files = Field('files', _$files);
static int? _$startTime(SendSessionState v) => v.startTime;
static const Field<SendSessionState, int> _f$startTime = Field('startTime', _$startTime);
static int? _$endTime(SendSessionState v) => v.endTime;
static const Field<SendSessionState, int> _f$endTime = Field('endTime', _$endTime);
static CancelToken? _$cancelToken(SendSessionState v) => v.cancelToken;
static const Field<SendSessionState, CancelToken> _f$cancelToken = Field('cancelToken', _$cancelToken);
static String? _$errorMessage(SendSessionState v) => v.errorMessage;
static const Field<SendSessionState, String> _f$errorMessage = Field('errorMessage', _$errorMessage);
@override
final MappableFields<SendSessionState> fields = const {
#sessionId: _f$sessionId,
#remoteSessionId: _f$remoteSessionId,
#background: _f$background,
#status: _f$status,
#target: _f$target,
#files: _f$files,
#startTime: _f$startTime,
#endTime: _f$endTime,
#cancelToken: _f$cancelToken,
#errorMessage: _f$errorMessage,
};
static SendSessionState _instantiate(DecodingData data) {
return SendSessionState(
sessionId: data.dec(_f$sessionId),
remoteSessionId: data.dec(_f$remoteSessionId),
background: data.dec(_f$background),
status: data.dec(_f$status),
target: data.dec(_f$target),
files: data.dec(_f$files),
startTime: data.dec(_f$startTime),
endTime: data.dec(_f$endTime),
cancelToken: data.dec(_f$cancelToken),
errorMessage: data.dec(_f$errorMessage));
}
@override
final Function instantiate = _instantiate;
static SendSessionState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<SendSessionState>(map);
}
static SendSessionState deserialize(String json) {
return ensureInitialized().decodeJson<SendSessionState>(json);
}
}
mixin SendSessionStateMappable {
String serialize() {
return SendSessionStateMapper.ensureInitialized().encodeJson<SendSessionState>(this as SendSessionState);
}
Map<String, dynamic> toJson() {
return SendSessionStateMapper.ensureInitialized().encodeMap<SendSessionState>(this as SendSessionState);
}
SendSessionStateCopyWith<SendSessionState, SendSessionState, SendSessionState> get copyWith =>
_SendSessionStateCopyWithImpl(this as SendSessionState, $identity, $identity);
@override
String toString() {
return SendSessionStateMapper.ensureInitialized().stringifyValue(this as SendSessionState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && SendSessionStateMapper.ensureInitialized().isValueEqual(this as SendSessionState, other));
}
@override
int get hashCode {
return SendSessionStateMapper.ensureInitialized().hashValue(this as SendSessionState);
}
}
extension SendSessionStateValueCopy<$R, $Out> on ObjectCopyWith<$R, SendSessionState, $Out> {
SendSessionStateCopyWith<$R, SendSessionState, $Out> get $asSendSessionState => $base.as((v, t, t2) => _SendSessionStateCopyWithImpl(v, t, t2));
}
abstract class SendSessionStateCopyWith<$R, $In extends SendSessionState, $Out> implements ClassCopyWith<$R, $In, $Out> {
DeviceCopyWith<$R, Device, Device> get target;
MapCopyWith<$R, String, SendingFile, SendingFileCopyWith<$R, SendingFile, SendingFile>> get files;
$R call(
{String? sessionId,
String? remoteSessionId,
bool? background,
SessionStatus? status,
Device? target,
Map<String, SendingFile>? files,
int? startTime,
int? endTime,
CancelToken? cancelToken,
String? errorMessage});
SendSessionStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _SendSessionStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, SendSessionState, $Out>
implements SendSessionStateCopyWith<$R, SendSessionState, $Out> {
_SendSessionStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<SendSessionState> $mapper = SendSessionStateMapper.ensureInitialized();
@override
DeviceCopyWith<$R, Device, Device> get target => $value.target.copyWith.$chain((v) => call(target: v));
@override
MapCopyWith<$R, String, SendingFile, SendingFileCopyWith<$R, SendingFile, SendingFile>> get files =>
MapCopyWith($value.files, (v, t) => v.copyWith.$chain(t), (v) => call(files: v));
@override
$R call(
{String? sessionId,
Object? remoteSessionId = $none,
bool? background,
SessionStatus? status,
Device? target,
Map<String, SendingFile>? files,
Object? startTime = $none,
Object? endTime = $none,
Object? cancelToken = $none,
Object? errorMessage = $none}) =>
$apply(FieldCopyWithData({
if (sessionId != null) #sessionId: sessionId,
if (remoteSessionId != $none) #remoteSessionId: remoteSessionId,
if (background != null) #background: background,
if (status != null) #status: status,
if (target != null) #target: target,
if (files != null) #files: files,
if (startTime != $none) #startTime: startTime,
if (endTime != $none) #endTime: endTime,
if (cancelToken != $none) #cancelToken: cancelToken,
if (errorMessage != $none) #errorMessage: errorMessage
}));
@override
SendSessionState $make(CopyWithData data) => SendSessionState(
sessionId: data.get(#sessionId, or: $value.sessionId),
remoteSessionId: data.get(#remoteSessionId, or: $value.remoteSessionId),
background: data.get(#background, or: $value.background),
status: data.get(#status, or: $value.status),
target: data.get(#target, or: $value.target),
files: data.get(#files, or: $value.files),
startTime: data.get(#startTime, or: $value.startTime),
endTime: data.get(#endTime, or: $value.endTime),
cancelToken: data.get(#cancelToken, or: $value.cancelToken),
errorMessage: data.get(#errorMessage, or: $value.errorMessage));
@override
SendSessionStateCopyWith<$R2, SendSessionState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _SendSessionStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state/send | mirrored_repositories/localsend/app/lib/model/state/send/web/web_send_file.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'web_send_file.dart';
class WebSendFileMapper extends ClassMapperBase<WebSendFile> {
WebSendFileMapper._();
static WebSendFileMapper? _instance;
static WebSendFileMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = WebSendFileMapper._());
}
return _instance!;
}
@override
final String id = 'WebSendFile';
static FileDto _$file(WebSendFile v) => v.file;
static const Field<WebSendFile, FileDto> _f$file = Field('file', _$file);
static AssetEntity? _$asset(WebSendFile v) => v.asset;
static const Field<WebSendFile, AssetEntity> _f$asset = Field('asset', _$asset);
static String? _$path(WebSendFile v) => v.path;
static const Field<WebSendFile, String> _f$path = Field('path', _$path);
static List<int>? _$bytes(WebSendFile v) => v.bytes;
static const Field<WebSendFile, List<int>> _f$bytes = Field('bytes', _$bytes);
@override
final MappableFields<WebSendFile> fields = const {
#file: _f$file,
#asset: _f$asset,
#path: _f$path,
#bytes: _f$bytes,
};
static WebSendFile _instantiate(DecodingData data) {
return WebSendFile(file: data.dec(_f$file), asset: data.dec(_f$asset), path: data.dec(_f$path), bytes: data.dec(_f$bytes));
}
@override
final Function instantiate = _instantiate;
static WebSendFile fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<WebSendFile>(map);
}
static WebSendFile deserialize(String json) {
return ensureInitialized().decodeJson<WebSendFile>(json);
}
}
mixin WebSendFileMappable {
String serialize() {
return WebSendFileMapper.ensureInitialized().encodeJson<WebSendFile>(this as WebSendFile);
}
Map<String, dynamic> toJson() {
return WebSendFileMapper.ensureInitialized().encodeMap<WebSendFile>(this as WebSendFile);
}
WebSendFileCopyWith<WebSendFile, WebSendFile, WebSendFile> get copyWith => _WebSendFileCopyWithImpl(this as WebSendFile, $identity, $identity);
@override
String toString() {
return WebSendFileMapper.ensureInitialized().stringifyValue(this as WebSendFile);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && WebSendFileMapper.ensureInitialized().isValueEqual(this as WebSendFile, other));
}
@override
int get hashCode {
return WebSendFileMapper.ensureInitialized().hashValue(this as WebSendFile);
}
}
extension WebSendFileValueCopy<$R, $Out> on ObjectCopyWith<$R, WebSendFile, $Out> {
WebSendFileCopyWith<$R, WebSendFile, $Out> get $asWebSendFile => $base.as((v, t, t2) => _WebSendFileCopyWithImpl(v, t, t2));
}
abstract class WebSendFileCopyWith<$R, $In extends WebSendFile, $Out> implements ClassCopyWith<$R, $In, $Out> {
ListCopyWith<$R, int, ObjectCopyWith<$R, int, int>>? get bytes;
$R call({FileDto? file, AssetEntity? asset, String? path, List<int>? bytes});
WebSendFileCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _WebSendFileCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, WebSendFile, $Out> implements WebSendFileCopyWith<$R, WebSendFile, $Out> {
_WebSendFileCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<WebSendFile> $mapper = WebSendFileMapper.ensureInitialized();
@override
ListCopyWith<$R, int, ObjectCopyWith<$R, int, int>>? get bytes =>
$value.bytes != null ? ListCopyWith($value.bytes!, (v, t) => ObjectCopyWith(v, $identity, t), (v) => call(bytes: v)) : null;
@override
$R call({FileDto? file, Object? asset = $none, Object? path = $none, Object? bytes = $none}) => $apply(FieldCopyWithData(
{if (file != null) #file: file, if (asset != $none) #asset: asset, if (path != $none) #path: path, if (bytes != $none) #bytes: bytes}));
@override
WebSendFile $make(CopyWithData data) => WebSendFile(
file: data.get(#file, or: $value.file),
asset: data.get(#asset, or: $value.asset),
path: data.get(#path, or: $value.path),
bytes: data.get(#bytes, or: $value.bytes));
@override
WebSendFileCopyWith<$R2, WebSendFile, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _WebSendFileCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state/send | mirrored_repositories/localsend/app/lib/model/state/send/web/web_send_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'web_send_state.dart';
class WebSendStateMapper extends ClassMapperBase<WebSendState> {
WebSendStateMapper._();
static WebSendStateMapper? _instance;
static WebSendStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = WebSendStateMapper._());
WebSendSessionMapper.ensureInitialized();
WebSendFileMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'WebSendState';
static Map<String, WebSendSession> _$sessions(WebSendState v) => v.sessions;
static const Field<WebSendState, Map<String, WebSendSession>> _f$sessions = Field('sessions', _$sessions);
static Map<String, WebSendFile> _$files(WebSendState v) => v.files;
static const Field<WebSendState, Map<String, WebSendFile>> _f$files = Field('files', _$files);
static bool _$autoAccept(WebSendState v) => v.autoAccept;
static const Field<WebSendState, bool> _f$autoAccept = Field('autoAccept', _$autoAccept);
@override
final MappableFields<WebSendState> fields = const {
#sessions: _f$sessions,
#files: _f$files,
#autoAccept: _f$autoAccept,
};
static WebSendState _instantiate(DecodingData data) {
return WebSendState(sessions: data.dec(_f$sessions), files: data.dec(_f$files), autoAccept: data.dec(_f$autoAccept));
}
@override
final Function instantiate = _instantiate;
static WebSendState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<WebSendState>(map);
}
static WebSendState deserialize(String json) {
return ensureInitialized().decodeJson<WebSendState>(json);
}
}
mixin WebSendStateMappable {
String serialize() {
return WebSendStateMapper.ensureInitialized().encodeJson<WebSendState>(this as WebSendState);
}
Map<String, dynamic> toJson() {
return WebSendStateMapper.ensureInitialized().encodeMap<WebSendState>(this as WebSendState);
}
WebSendStateCopyWith<WebSendState, WebSendState, WebSendState> get copyWith =>
_WebSendStateCopyWithImpl(this as WebSendState, $identity, $identity);
@override
String toString() {
return WebSendStateMapper.ensureInitialized().stringifyValue(this as WebSendState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && WebSendStateMapper.ensureInitialized().isValueEqual(this as WebSendState, other));
}
@override
int get hashCode {
return WebSendStateMapper.ensureInitialized().hashValue(this as WebSendState);
}
}
extension WebSendStateValueCopy<$R, $Out> on ObjectCopyWith<$R, WebSendState, $Out> {
WebSendStateCopyWith<$R, WebSendState, $Out> get $asWebSendState => $base.as((v, t, t2) => _WebSendStateCopyWithImpl(v, t, t2));
}
abstract class WebSendStateCopyWith<$R, $In extends WebSendState, $Out> implements ClassCopyWith<$R, $In, $Out> {
MapCopyWith<$R, String, WebSendSession, WebSendSessionCopyWith<$R, WebSendSession, WebSendSession>> get sessions;
MapCopyWith<$R, String, WebSendFile, WebSendFileCopyWith<$R, WebSendFile, WebSendFile>> get files;
$R call({Map<String, WebSendSession>? sessions, Map<String, WebSendFile>? files, bool? autoAccept});
WebSendStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _WebSendStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, WebSendState, $Out> implements WebSendStateCopyWith<$R, WebSendState, $Out> {
_WebSendStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<WebSendState> $mapper = WebSendStateMapper.ensureInitialized();
@override
MapCopyWith<$R, String, WebSendSession, WebSendSessionCopyWith<$R, WebSendSession, WebSendSession>> get sessions =>
MapCopyWith($value.sessions, (v, t) => v.copyWith.$chain(t), (v) => call(sessions: v));
@override
MapCopyWith<$R, String, WebSendFile, WebSendFileCopyWith<$R, WebSendFile, WebSendFile>> get files =>
MapCopyWith($value.files, (v, t) => v.copyWith.$chain(t), (v) => call(files: v));
@override
$R call({Map<String, WebSendSession>? sessions, Map<String, WebSendFile>? files, bool? autoAccept}) => $apply(FieldCopyWithData(
{if (sessions != null) #sessions: sessions, if (files != null) #files: files, if (autoAccept != null) #autoAccept: autoAccept}));
@override
WebSendState $make(CopyWithData data) => WebSendState(
sessions: data.get(#sessions, or: $value.sessions),
files: data.get(#files, or: $value.files),
autoAccept: data.get(#autoAccept, or: $value.autoAccept));
@override
WebSendStateCopyWith<$R2, WebSendState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _WebSendStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state/send | mirrored_repositories/localsend/app/lib/model/state/send/web/web_send_state.dart | import 'package:dart_mappable/dart_mappable.dart';
import 'package:localsend_app/model/state/send/web/web_send_file.dart';
import 'package:localsend_app/model/state/send/web/web_send_session.dart';
part 'web_send_state.mapper.dart';
@MappableClass()
class WebSendState with WebSendStateMappable {
final Map<String, WebSendSession> sessions; // session id -> session data, also includes incoming requests
final Map<String, WebSendFile> files; // file id as key
final bool autoAccept; // automatically accept incoming requests
const WebSendState({
required this.sessions,
required this.files,
required this.autoAccept,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state/send | mirrored_repositories/localsend/app/lib/model/state/send/web/web_send_session.dart | import 'dart:async';
import 'package:dart_mappable/dart_mappable.dart';
part 'web_send_session.mapper.dart';
@MappableClass()
class WebSendSession with WebSendSessionMappable {
final String sessionId;
final StreamController<bool>? responseHandler; // used to accept or reject incoming requests
final String ip;
final String deviceInfo; // parsed from userAgent
const WebSendSession({
required this.sessionId,
required this.responseHandler,
required this.ip,
required this.deviceInfo,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state/send | mirrored_repositories/localsend/app/lib/model/state/send/web/web_send_file.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
part 'web_send_file.mapper.dart';
@MappableClass()
class WebSendFile with WebSendFileMappable {
final FileDto file;
final AssetEntity? asset; // for thumbnails
final String? path; // android, iOS, desktop
final List<int>? bytes; // web
const WebSendFile({
required this.file,
required this.asset,
required this.path,
required this.bytes,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state/send | mirrored_repositories/localsend/app/lib/model/state/send/web/web_send_session.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'web_send_session.dart';
class WebSendSessionMapper extends ClassMapperBase<WebSendSession> {
WebSendSessionMapper._();
static WebSendSessionMapper? _instance;
static WebSendSessionMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = WebSendSessionMapper._());
}
return _instance!;
}
@override
final String id = 'WebSendSession';
static String _$sessionId(WebSendSession v) => v.sessionId;
static const Field<WebSendSession, String> _f$sessionId = Field('sessionId', _$sessionId);
static StreamController<bool>? _$responseHandler(WebSendSession v) => v.responseHandler;
static const Field<WebSendSession, StreamController<bool>> _f$responseHandler = Field('responseHandler', _$responseHandler);
static String _$ip(WebSendSession v) => v.ip;
static const Field<WebSendSession, String> _f$ip = Field('ip', _$ip);
static String _$deviceInfo(WebSendSession v) => v.deviceInfo;
static const Field<WebSendSession, String> _f$deviceInfo = Field('deviceInfo', _$deviceInfo);
@override
final MappableFields<WebSendSession> fields = const {
#sessionId: _f$sessionId,
#responseHandler: _f$responseHandler,
#ip: _f$ip,
#deviceInfo: _f$deviceInfo,
};
static WebSendSession _instantiate(DecodingData data) {
return WebSendSession(
sessionId: data.dec(_f$sessionId), responseHandler: data.dec(_f$responseHandler), ip: data.dec(_f$ip), deviceInfo: data.dec(_f$deviceInfo));
}
@override
final Function instantiate = _instantiate;
static WebSendSession fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<WebSendSession>(map);
}
static WebSendSession deserialize(String json) {
return ensureInitialized().decodeJson<WebSendSession>(json);
}
}
mixin WebSendSessionMappable {
String serialize() {
return WebSendSessionMapper.ensureInitialized().encodeJson<WebSendSession>(this as WebSendSession);
}
Map<String, dynamic> toJson() {
return WebSendSessionMapper.ensureInitialized().encodeMap<WebSendSession>(this as WebSendSession);
}
WebSendSessionCopyWith<WebSendSession, WebSendSession, WebSendSession> get copyWith =>
_WebSendSessionCopyWithImpl(this as WebSendSession, $identity, $identity);
@override
String toString() {
return WebSendSessionMapper.ensureInitialized().stringifyValue(this as WebSendSession);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && WebSendSessionMapper.ensureInitialized().isValueEqual(this as WebSendSession, other));
}
@override
int get hashCode {
return WebSendSessionMapper.ensureInitialized().hashValue(this as WebSendSession);
}
}
extension WebSendSessionValueCopy<$R, $Out> on ObjectCopyWith<$R, WebSendSession, $Out> {
WebSendSessionCopyWith<$R, WebSendSession, $Out> get $asWebSendSession => $base.as((v, t, t2) => _WebSendSessionCopyWithImpl(v, t, t2));
}
abstract class WebSendSessionCopyWith<$R, $In extends WebSendSession, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call({String? sessionId, StreamController<bool>? responseHandler, String? ip, String? deviceInfo});
WebSendSessionCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _WebSendSessionCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, WebSendSession, $Out>
implements WebSendSessionCopyWith<$R, WebSendSession, $Out> {
_WebSendSessionCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<WebSendSession> $mapper = WebSendSessionMapper.ensureInitialized();
@override
$R call({String? sessionId, Object? responseHandler = $none, String? ip, String? deviceInfo}) => $apply(FieldCopyWithData({
if (sessionId != null) #sessionId: sessionId,
if (responseHandler != $none) #responseHandler: responseHandler,
if (ip != null) #ip: ip,
if (deviceInfo != null) #deviceInfo: deviceInfo
}));
@override
WebSendSession $make(CopyWithData data) => WebSendSession(
sessionId: data.get(#sessionId, or: $value.sessionId),
responseHandler: data.get(#responseHandler, or: $value.responseHandler),
ip: data.get(#ip, or: $value.ip),
deviceInfo: data.get(#deviceInfo, or: $value.deviceInfo));
@override
WebSendSessionCopyWith<$R2, WebSendSession, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _WebSendSessionCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/server/receiving_file.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'receiving_file.dart';
class ReceivingFileMapper extends ClassMapperBase<ReceivingFile> {
ReceivingFileMapper._();
static ReceivingFileMapper? _instance;
static ReceivingFileMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = ReceivingFileMapper._());
}
return _instance!;
}
@override
final String id = 'ReceivingFile';
static FileDto _$file(ReceivingFile v) => v.file;
static const Field<ReceivingFile, FileDto> _f$file = Field('file', _$file);
static FileStatus _$status(ReceivingFile v) => v.status;
static const Field<ReceivingFile, FileStatus> _f$status = Field('status', _$status);
static String? _$token(ReceivingFile v) => v.token;
static const Field<ReceivingFile, String> _f$token = Field('token', _$token);
static String? _$desiredName(ReceivingFile v) => v.desiredName;
static const Field<ReceivingFile, String> _f$desiredName = Field('desiredName', _$desiredName);
static String? _$path(ReceivingFile v) => v.path;
static const Field<ReceivingFile, String> _f$path = Field('path', _$path);
static bool _$savedToGallery(ReceivingFile v) => v.savedToGallery;
static const Field<ReceivingFile, bool> _f$savedToGallery = Field('savedToGallery', _$savedToGallery);
static String? _$errorMessage(ReceivingFile v) => v.errorMessage;
static const Field<ReceivingFile, String> _f$errorMessage = Field('errorMessage', _$errorMessage);
@override
final MappableFields<ReceivingFile> fields = const {
#file: _f$file,
#status: _f$status,
#token: _f$token,
#desiredName: _f$desiredName,
#path: _f$path,
#savedToGallery: _f$savedToGallery,
#errorMessage: _f$errorMessage,
};
static ReceivingFile _instantiate(DecodingData data) {
return ReceivingFile(
file: data.dec(_f$file),
status: data.dec(_f$status),
token: data.dec(_f$token),
desiredName: data.dec(_f$desiredName),
path: data.dec(_f$path),
savedToGallery: data.dec(_f$savedToGallery),
errorMessage: data.dec(_f$errorMessage));
}
@override
final Function instantiate = _instantiate;
static ReceivingFile fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<ReceivingFile>(map);
}
static ReceivingFile deserialize(String json) {
return ensureInitialized().decodeJson<ReceivingFile>(json);
}
}
mixin ReceivingFileMappable {
String serialize() {
return ReceivingFileMapper.ensureInitialized().encodeJson<ReceivingFile>(this as ReceivingFile);
}
Map<String, dynamic> toJson() {
return ReceivingFileMapper.ensureInitialized().encodeMap<ReceivingFile>(this as ReceivingFile);
}
ReceivingFileCopyWith<ReceivingFile, ReceivingFile, ReceivingFile> get copyWith =>
_ReceivingFileCopyWithImpl(this as ReceivingFile, $identity, $identity);
@override
String toString() {
return ReceivingFileMapper.ensureInitialized().stringifyValue(this as ReceivingFile);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && ReceivingFileMapper.ensureInitialized().isValueEqual(this as ReceivingFile, other));
}
@override
int get hashCode {
return ReceivingFileMapper.ensureInitialized().hashValue(this as ReceivingFile);
}
}
extension ReceivingFileValueCopy<$R, $Out> on ObjectCopyWith<$R, ReceivingFile, $Out> {
ReceivingFileCopyWith<$R, ReceivingFile, $Out> get $asReceivingFile => $base.as((v, t, t2) => _ReceivingFileCopyWithImpl(v, t, t2));
}
abstract class ReceivingFileCopyWith<$R, $In extends ReceivingFile, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call({FileDto? file, FileStatus? status, String? token, String? desiredName, String? path, bool? savedToGallery, String? errorMessage});
ReceivingFileCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _ReceivingFileCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, ReceivingFile, $Out>
implements ReceivingFileCopyWith<$R, ReceivingFile, $Out> {
_ReceivingFileCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<ReceivingFile> $mapper = ReceivingFileMapper.ensureInitialized();
@override
$R call(
{FileDto? file,
FileStatus? status,
Object? token = $none,
Object? desiredName = $none,
Object? path = $none,
bool? savedToGallery,
Object? errorMessage = $none}) =>
$apply(FieldCopyWithData({
if (file != null) #file: file,
if (status != null) #status: status,
if (token != $none) #token: token,
if (desiredName != $none) #desiredName: desiredName,
if (path != $none) #path: path,
if (savedToGallery != null) #savedToGallery: savedToGallery,
if (errorMessage != $none) #errorMessage: errorMessage
}));
@override
ReceivingFile $make(CopyWithData data) => ReceivingFile(
file: data.get(#file, or: $value.file),
status: data.get(#status, or: $value.status),
token: data.get(#token, or: $value.token),
desiredName: data.get(#desiredName, or: $value.desiredName),
path: data.get(#path, or: $value.path),
savedToGallery: data.get(#savedToGallery, or: $value.savedToGallery),
errorMessage: data.get(#errorMessage, or: $value.errorMessage));
@override
ReceivingFileCopyWith<$R2, ReceivingFile, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _ReceivingFileCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/server/receive_session_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'receive_session_state.dart';
class ReceiveSessionStateMapper extends ClassMapperBase<ReceiveSessionState> {
ReceiveSessionStateMapper._();
static ReceiveSessionStateMapper? _instance;
static ReceiveSessionStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = ReceiveSessionStateMapper._());
DeviceMapper.ensureInitialized();
ReceivingFileMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'ReceiveSessionState';
static String _$sessionId(ReceiveSessionState v) => v.sessionId;
static const Field<ReceiveSessionState, String> _f$sessionId = Field('sessionId', _$sessionId);
static SessionStatus _$status(ReceiveSessionState v) => v.status;
static const Field<ReceiveSessionState, SessionStatus> _f$status = Field('status', _$status);
static Device _$sender(ReceiveSessionState v) => v.sender;
static const Field<ReceiveSessionState, Device> _f$sender = Field('sender', _$sender);
static String _$senderAlias(ReceiveSessionState v) => v.senderAlias;
static const Field<ReceiveSessionState, String> _f$senderAlias = Field('senderAlias', _$senderAlias);
static Map<String, ReceivingFile> _$files(ReceiveSessionState v) => v.files;
static const Field<ReceiveSessionState, Map<String, ReceivingFile>> _f$files = Field('files', _$files);
static int? _$startTime(ReceiveSessionState v) => v.startTime;
static const Field<ReceiveSessionState, int> _f$startTime = Field('startTime', _$startTime);
static int? _$endTime(ReceiveSessionState v) => v.endTime;
static const Field<ReceiveSessionState, int> _f$endTime = Field('endTime', _$endTime);
static String _$destinationDirectory(ReceiveSessionState v) => v.destinationDirectory;
static const Field<ReceiveSessionState, String> _f$destinationDirectory = Field('destinationDirectory', _$destinationDirectory);
static String _$cacheDirectory(ReceiveSessionState v) => v.cacheDirectory;
static const Field<ReceiveSessionState, String> _f$cacheDirectory = Field('cacheDirectory', _$cacheDirectory);
static bool _$saveToGallery(ReceiveSessionState v) => v.saveToGallery;
static const Field<ReceiveSessionState, bool> _f$saveToGallery = Field('saveToGallery', _$saveToGallery);
static StreamController<Map<String, String>?>? _$responseHandler(ReceiveSessionState v) => v.responseHandler;
static const Field<ReceiveSessionState, StreamController<Map<String, String>?>> _f$responseHandler = Field('responseHandler', _$responseHandler);
@override
final MappableFields<ReceiveSessionState> fields = const {
#sessionId: _f$sessionId,
#status: _f$status,
#sender: _f$sender,
#senderAlias: _f$senderAlias,
#files: _f$files,
#startTime: _f$startTime,
#endTime: _f$endTime,
#destinationDirectory: _f$destinationDirectory,
#cacheDirectory: _f$cacheDirectory,
#saveToGallery: _f$saveToGallery,
#responseHandler: _f$responseHandler,
};
static ReceiveSessionState _instantiate(DecodingData data) {
return ReceiveSessionState(
sessionId: data.dec(_f$sessionId),
status: data.dec(_f$status),
sender: data.dec(_f$sender),
senderAlias: data.dec(_f$senderAlias),
files: data.dec(_f$files),
startTime: data.dec(_f$startTime),
endTime: data.dec(_f$endTime),
destinationDirectory: data.dec(_f$destinationDirectory),
cacheDirectory: data.dec(_f$cacheDirectory),
saveToGallery: data.dec(_f$saveToGallery),
responseHandler: data.dec(_f$responseHandler));
}
@override
final Function instantiate = _instantiate;
static ReceiveSessionState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<ReceiveSessionState>(map);
}
static ReceiveSessionState deserialize(String json) {
return ensureInitialized().decodeJson<ReceiveSessionState>(json);
}
}
mixin ReceiveSessionStateMappable {
String serialize() {
return ReceiveSessionStateMapper.ensureInitialized().encodeJson<ReceiveSessionState>(this as ReceiveSessionState);
}
Map<String, dynamic> toJson() {
return ReceiveSessionStateMapper.ensureInitialized().encodeMap<ReceiveSessionState>(this as ReceiveSessionState);
}
ReceiveSessionStateCopyWith<ReceiveSessionState, ReceiveSessionState, ReceiveSessionState> get copyWith =>
_ReceiveSessionStateCopyWithImpl(this as ReceiveSessionState, $identity, $identity);
@override
String toString() {
return ReceiveSessionStateMapper.ensureInitialized().stringifyValue(this as ReceiveSessionState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && ReceiveSessionStateMapper.ensureInitialized().isValueEqual(this as ReceiveSessionState, other));
}
@override
int get hashCode {
return ReceiveSessionStateMapper.ensureInitialized().hashValue(this as ReceiveSessionState);
}
}
extension ReceiveSessionStateValueCopy<$R, $Out> on ObjectCopyWith<$R, ReceiveSessionState, $Out> {
ReceiveSessionStateCopyWith<$R, ReceiveSessionState, $Out> get $asReceiveSessionState =>
$base.as((v, t, t2) => _ReceiveSessionStateCopyWithImpl(v, t, t2));
}
abstract class ReceiveSessionStateCopyWith<$R, $In extends ReceiveSessionState, $Out> implements ClassCopyWith<$R, $In, $Out> {
DeviceCopyWith<$R, Device, Device> get sender;
MapCopyWith<$R, String, ReceivingFile, ReceivingFileCopyWith<$R, ReceivingFile, ReceivingFile>> get files;
$R call(
{String? sessionId,
SessionStatus? status,
Device? sender,
String? senderAlias,
Map<String, ReceivingFile>? files,
int? startTime,
int? endTime,
String? destinationDirectory,
String? cacheDirectory,
bool? saveToGallery,
StreamController<Map<String, String>?>? responseHandler});
ReceiveSessionStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _ReceiveSessionStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, ReceiveSessionState, $Out>
implements ReceiveSessionStateCopyWith<$R, ReceiveSessionState, $Out> {
_ReceiveSessionStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<ReceiveSessionState> $mapper = ReceiveSessionStateMapper.ensureInitialized();
@override
DeviceCopyWith<$R, Device, Device> get sender => $value.sender.copyWith.$chain((v) => call(sender: v));
@override
MapCopyWith<$R, String, ReceivingFile, ReceivingFileCopyWith<$R, ReceivingFile, ReceivingFile>> get files =>
MapCopyWith($value.files, (v, t) => v.copyWith.$chain(t), (v) => call(files: v));
@override
$R call(
{String? sessionId,
SessionStatus? status,
Device? sender,
String? senderAlias,
Map<String, ReceivingFile>? files,
Object? startTime = $none,
Object? endTime = $none,
String? destinationDirectory,
String? cacheDirectory,
bool? saveToGallery,
Object? responseHandler = $none}) =>
$apply(FieldCopyWithData({
if (sessionId != null) #sessionId: sessionId,
if (status != null) #status: status,
if (sender != null) #sender: sender,
if (senderAlias != null) #senderAlias: senderAlias,
if (files != null) #files: files,
if (startTime != $none) #startTime: startTime,
if (endTime != $none) #endTime: endTime,
if (destinationDirectory != null) #destinationDirectory: destinationDirectory,
if (cacheDirectory != null) #cacheDirectory: cacheDirectory,
if (saveToGallery != null) #saveToGallery: saveToGallery,
if (responseHandler != $none) #responseHandler: responseHandler
}));
@override
ReceiveSessionState $make(CopyWithData data) => ReceiveSessionState(
sessionId: data.get(#sessionId, or: $value.sessionId),
status: data.get(#status, or: $value.status),
sender: data.get(#sender, or: $value.sender),
senderAlias: data.get(#senderAlias, or: $value.senderAlias),
files: data.get(#files, or: $value.files),
startTime: data.get(#startTime, or: $value.startTime),
endTime: data.get(#endTime, or: $value.endTime),
destinationDirectory: data.get(#destinationDirectory, or: $value.destinationDirectory),
cacheDirectory: data.get(#cacheDirectory, or: $value.cacheDirectory),
saveToGallery: data.get(#saveToGallery, or: $value.saveToGallery),
responseHandler: data.get(#responseHandler, or: $value.responseHandler));
@override
ReceiveSessionStateCopyWith<$R2, ReceiveSessionState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_ReceiveSessionStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/server/receive_session_state.dart | import 'dart:async';
import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:localsend_app/model/state/server/receiving_file.dart';
part 'receive_session_state.mapper.dart';
@MappableClass()
class ReceiveSessionState with ReceiveSessionStateMappable {
final String sessionId;
final SessionStatus status;
final Device sender;
// Might not be the same as sender.alias since it can be overridden as a favorite
final String senderAlias;
final Map<String, ReceivingFile> files; // file id as key
final int? startTime;
final int? endTime;
final String destinationDirectory;
final String cacheDirectory;
final bool saveToGallery;
final StreamController<Map<String, String>?>? responseHandler;
const ReceiveSessionState({
required this.sessionId,
required this.status,
required this.sender,
required this.senderAlias,
required this.files,
required this.startTime,
required this.endTime,
required this.destinationDirectory,
required this.cacheDirectory,
required this.saveToGallery,
required this.responseHandler,
});
/// Returns the message of this request if this is a "message request".
/// Message requests must contain a single text file with preview included.
String? get message {
final firstFile = files.values.first.file;
return files.length == 1 && firstFile.fileType == FileType.text ? firstFile.preview : null;
}
/// Returns true if this request contains files having a directory path.
/// "Save to gallery" is disabled for such requests.
bool get containsDirectories {
return files.values.any((f) => f.file.fileName.contains('/'));
}
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/server/server_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'server_state.dart';
class ServerStateMapper extends ClassMapperBase<ServerState> {
ServerStateMapper._();
static ServerStateMapper? _instance;
static ServerStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = ServerStateMapper._());
ReceiveSessionStateMapper.ensureInitialized();
WebSendStateMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'ServerState';
static HttpServer _$httpServer(ServerState v) => v.httpServer;
static const Field<ServerState, HttpServer> _f$httpServer = Field('httpServer', _$httpServer);
static String _$alias(ServerState v) => v.alias;
static const Field<ServerState, String> _f$alias = Field('alias', _$alias);
static int _$port(ServerState v) => v.port;
static const Field<ServerState, int> _f$port = Field('port', _$port);
static bool _$https(ServerState v) => v.https;
static const Field<ServerState, bool> _f$https = Field('https', _$https);
static ReceiveSessionState? _$session(ServerState v) => v.session;
static const Field<ServerState, ReceiveSessionState> _f$session = Field('session', _$session);
static WebSendState? _$webSendState(ServerState v) => v.webSendState;
static const Field<ServerState, WebSendState> _f$webSendState = Field('webSendState', _$webSendState);
@override
final MappableFields<ServerState> fields = const {
#httpServer: _f$httpServer,
#alias: _f$alias,
#port: _f$port,
#https: _f$https,
#session: _f$session,
#webSendState: _f$webSendState,
};
static ServerState _instantiate(DecodingData data) {
return ServerState(
httpServer: data.dec(_f$httpServer),
alias: data.dec(_f$alias),
port: data.dec(_f$port),
https: data.dec(_f$https),
session: data.dec(_f$session),
webSendState: data.dec(_f$webSendState));
}
@override
final Function instantiate = _instantiate;
static ServerState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<ServerState>(map);
}
static ServerState deserialize(String json) {
return ensureInitialized().decodeJson<ServerState>(json);
}
}
mixin ServerStateMappable {
String serialize() {
return ServerStateMapper.ensureInitialized().encodeJson<ServerState>(this as ServerState);
}
Map<String, dynamic> toJson() {
return ServerStateMapper.ensureInitialized().encodeMap<ServerState>(this as ServerState);
}
ServerStateCopyWith<ServerState, ServerState, ServerState> get copyWith => _ServerStateCopyWithImpl(this as ServerState, $identity, $identity);
@override
String toString() {
return ServerStateMapper.ensureInitialized().stringifyValue(this as ServerState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && ServerStateMapper.ensureInitialized().isValueEqual(this as ServerState, other));
}
@override
int get hashCode {
return ServerStateMapper.ensureInitialized().hashValue(this as ServerState);
}
}
extension ServerStateValueCopy<$R, $Out> on ObjectCopyWith<$R, ServerState, $Out> {
ServerStateCopyWith<$R, ServerState, $Out> get $asServerState => $base.as((v, t, t2) => _ServerStateCopyWithImpl(v, t, t2));
}
abstract class ServerStateCopyWith<$R, $In extends ServerState, $Out> implements ClassCopyWith<$R, $In, $Out> {
ReceiveSessionStateCopyWith<$R, ReceiveSessionState, ReceiveSessionState>? get session;
WebSendStateCopyWith<$R, WebSendState, WebSendState>? get webSendState;
$R call({HttpServer? httpServer, String? alias, int? port, bool? https, ReceiveSessionState? session, WebSendState? webSendState});
ServerStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _ServerStateCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, ServerState, $Out> implements ServerStateCopyWith<$R, ServerState, $Out> {
_ServerStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<ServerState> $mapper = ServerStateMapper.ensureInitialized();
@override
ReceiveSessionStateCopyWith<$R, ReceiveSessionState, ReceiveSessionState>? get session => $value.session?.copyWith.$chain((v) => call(session: v));
@override
WebSendStateCopyWith<$R, WebSendState, WebSendState>? get webSendState => $value.webSendState?.copyWith.$chain((v) => call(webSendState: v));
@override
$R call({HttpServer? httpServer, String? alias, int? port, bool? https, Object? session = $none, Object? webSendState = $none}) =>
$apply(FieldCopyWithData({
if (httpServer != null) #httpServer: httpServer,
if (alias != null) #alias: alias,
if (port != null) #port: port,
if (https != null) #https: https,
if (session != $none) #session: session,
if (webSendState != $none) #webSendState: webSendState
}));
@override
ServerState $make(CopyWithData data) => ServerState(
httpServer: data.get(#httpServer, or: $value.httpServer),
alias: data.get(#alias, or: $value.alias),
port: data.get(#port, or: $value.port),
https: data.get(#https, or: $value.https),
session: data.get(#session, or: $value.session),
webSendState: data.get(#webSendState, or: $value.webSendState));
@override
ServerStateCopyWith<$R2, ServerState, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _ServerStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/server/receiving_file.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'receiving_file.mapper.dart';
@MappableClass()
class ReceivingFile with ReceivingFileMappable {
final FileDto file;
final FileStatus status;
final String? token;
final String? desiredName; // not null when accepted
final String? path; // when finished
final bool savedToGallery; // when finished
final String? errorMessage; // when status == failed
const ReceivingFile({
required this.file,
required this.status,
required this.token,
required this.desiredName,
required this.path,
required this.savedToGallery,
required this.errorMessage,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/model/state | mirrored_repositories/localsend/app/lib/model/state/server/server_state.dart | import 'dart:io';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:localsend_app/model/state/send/web/web_send_state.dart';
import 'package:localsend_app/model/state/server/receive_session_state.dart';
part 'server_state.mapper.dart';
@MappableClass()
class ServerState with ServerStateMappable {
final HttpServer httpServer;
final String alias;
final int port;
final bool https;
final ReceiveSessionState? session;
final WebSendState? webSendState;
const ServerState({
required this.httpServer,
required this.alias,
required this.port,
required this.https,
required this.session,
required this.webSendState,
});
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/shared_preferences_portable.dart | import 'dart:convert';
import 'dart:io';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
const _encoder = JsonEncoder.withIndent(' ');
/// Custom implementation of SharedPreferencesStorePlatform
/// that uses a file named settings.json located next to the executable.
/// This is used to for portable mode.
class SharedPreferencesPortable extends SharedPreferencesStorePlatform {
static final _file = File('settings.json');
late final Map<String, Object> _cache = _getAll();
static bool exists() {
return _file.existsSync();
}
@override
Future<bool> clear() {
_write({});
return Future.value(true);
}
@override
Future<Map<String, Object>> getAll() async {
return _cache;
}
Map<String, Object> _getAll() {
if (!_file.existsSync()) {
_file.createSync();
}
try {
return json.decode(_file.readAsStringSync()).cast<String, Object>();
} catch (e) {
return {};
}
}
@override
Future<bool> remove(String key) {
_cache.remove(key);
_write(_cache);
return Future.value(true);
}
@override
Future<bool> setValue(String valueType, String key, Object value) {
_cache[key] = value;
_write(_cache);
return Future.value(true);
}
void _write(Map<String, dynamic> data) {
if (!_file.existsSync()) {
_file.createSync(recursive: true);
}
_file.writeAsStringSync(_encoder.convert(data));
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/ip_helper.dart | import 'package:collection/collection.dart';
extension StringIpExt on String {
String get visualId => split('.').last;
}
class IpHelper {
/// Sorts Ip addresses with first being the most likely primary local address
/// Currently,
/// - sorts ending with ".1" last
/// - primary is always first
static List<String> rankIpAddresses(List<String> addresses, String primary) {
return addresses.sorted((a, b) {
int scoreA = a == primary ? 10 : (a.endsWith('.1') ? 0 : 1);
int scoreB = b == primary ? 10 : (b.endsWith('.1') ? 0 : 1);
return scoreB.compareTo(scoreA);
});
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/task_runner.dart | import 'dart:async';
import 'dart:collection';
typedef FutureFunction<T> = Future<T> Function();
class TaskRunner<T> {
final StreamController<T> _streamController = StreamController();
final Queue<FutureFunction<T>> _queue;
final int concurrency;
int _runnerCount = 0;
bool _stopped = false;
/// If [true], then the stream will be closed as soon as every task has been finished.
/// By default, it is [false] when [initialTasks] is provided with a non-empty list.
final bool _stayAlive;
final void Function()? onFinish;
TaskRunner({
required this.concurrency,
List<FutureFunction<T>>? initialTasks,
bool? stayAlive,
this.onFinish,
}) : _queue = Queue()..addAll(initialTasks ?? []),
_stayAlive = stayAlive ?? initialTasks == null || initialTasks.isEmpty {
_fireRunners();
}
void addAll(Iterable<FutureFunction<T>> iterable) {
_queue.addAll(iterable);
_fireRunners();
}
void stop() {
_stopped = true;
}
Stream<T> get stream => _streamController.stream;
/// Starts multiple runners until [concurrency].
void _fireRunners() {
while (_queue.isNotEmpty && _runnerCount < concurrency && !_streamController.isClosed) {
_runnerCount++;
unawaited(
_runner(
onFinish: () {
_runnerCount--;
if (_stopped || (_runnerCount == 0 && !_stayAlive)) {
_streamController.close();
onFinish?.call();
}
},
),
);
}
}
/// Processes the queue one by one.
Future<void> _runner({required void Function() onFinish}) async {
while (_queue.isNotEmpty) {
final task = _queue.removeFirst();
_streamController.add(await task());
}
onFinish();
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/logger.dart | import 'package:logging/logging.dart';
void initLogger(Level level) {
Logger.root.level = level;
Logger.root.onRecord.listen((record) {
// ignore: avoid_print
print('${record.time} ${'[${record.level.name}]'.padLeft(9)} [${record.loggerName}] ${record.message}');
if (record.error != null) {
// ignore: avoid_print
print(record.error);
}
if (record.stackTrace != null) {
// ignore: avoid_print
print(record.stackTrace);
}
});
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/file_type_ext.dart | import 'package:common/common.dart';
import 'package:flutter/material.dart';
extension FileTypeExt on FileType {
IconData get icon {
return switch (this) {
FileType.image => Icons.image,
FileType.video => Icons.movie,
FileType.pdf => Icons.description,
FileType.text => Icons.subject,
FileType.apk => Icons.android,
FileType.other => Icons.file_present_sharp,
};
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/i18n.dart | import 'package:localsend_app/gen/strings.g.dart';
void initI18n() {
// Register default plural resolver
for (final locale in AppLocale.values) {
if ([AppLocale.en, AppLocale.de].contains(locale)) {
continue;
}
LocaleSettings.setPluralResolver(
locale: locale,
cardinalResolver: (n, {zero, one, two, few, many, other}) {
if (n == 0) {
return zero ?? other ?? n.toString();
}
if (n == 1) {
return one ?? other ?? n.toString();
}
return other ?? n.toString();
},
ordinalResolver: (n, {zero, one, two, few, many, other}) {
return other ?? n.toString();
},
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/alias_generator.dart | import 'dart:math';
import 'package:localsend_app/gen/strings.g.dart';
String generateRandomAlias() {
final random = Random();
final adj = t.aliasGenerator.adjectives;
final fruits = t.aliasGenerator.fruits;
// The combination of both is locale dependent too.
return t.aliasGenerator.combination(
adjective: adj[random.nextInt(adj.length)],
fruit: fruits[random.nextInt(fruits.length)],
);
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/platform_strings.dart | import 'package:flutter/foundation.dart';
extension TargetPlatformExt on TargetPlatform {
String get humanName {
switch (this) {
case TargetPlatform.android:
return 'Android';
case TargetPlatform.fuchsia:
return 'Fuchsia';
case TargetPlatform.iOS:
return 'iOS';
case TargetPlatform.linux:
return 'Linux';
case TargetPlatform.macOS:
return 'macOS';
case TargetPlatform.windows:
return 'Windows';
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/file_speed_helper.dart | /// Returns bytes per second
int getFileSpeed({
required int start,
required int end,
required int bytes,
}) {
final deltaTime = end - start;
return (1000 * bytes) ~/ deltaTime; // multiply by 1000 to convert millis to seconds
}
/// Returns remaining time in m:ss
String getRemainingTime({
required int bytesPerSeconds,
required int remainingBytes,
}) {
final totalSeconds = _getRemainingTime(bytesPerSeconds: bytesPerSeconds, remainingBytes: remainingBytes);
final minutes = totalSeconds ~/ 60;
final seconds = totalSeconds % 60;
return '$minutes:${seconds.toString().padLeft(2, '0')}';
}
/// Returns remaining time in seconds
int _getRemainingTime({
required int bytesPerSeconds,
required int remainingBytes,
}) {
return remainingBytes ~/ bytesPerSeconds;
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/sleep.dart | Future<void> sleepAsync(int millis) {
return Future.delayed(Duration(milliseconds: millis), () {});
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/file_size_helper.dart | extension IntFileSize on int {
/// Converts the integer representing bytes to a readable string
String get asReadableFileSize {
if (this < 1024) {
return '$this B';
} else if (this < 1024 * 1024) {
return '${(this / 1024).toStringAsFixed(1)} KB';
} else if (this < 1024 * 1024 * 1024) {
return '${(this / (1024 * 1024)).toStringAsFixed(1)} MB';
} else {
return '${(this / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/device_type_ext.dart | import 'package:common/common.dart';
import 'package:flutter/material.dart';
extension DeviceTypeExt on DeviceType {
IconData get icon {
return switch (this) {
DeviceType.mobile => Icons.smartphone,
DeviceType.desktop => Icons.computer,
DeviceType.web => Icons.language,
DeviceType.headless => Icons.terminal,
DeviceType.server => Icons.dns,
};
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/user_agent_analyzer.dart | class UserAgentAnalyzer {
String? getBrowser(String userAgent) {
if (userAgent.contains('Firefox')) {
return 'Firefox';
} else if (userAgent.contains('Chrome')) {
return 'Chrome';
} else if (userAgent.contains('Safari')) {
return 'Safari';
} else if (userAgent.contains('Opera') || userAgent.contains('OPR')) {
return 'Opera';
} else if (userAgent.contains('Edg')) {
return 'Edge';
} else if (userAgent.contains('MSIE') || userAgent.contains('Trident')) {
return 'Internet Explorer';
} else if (userAgent.contains('insomnia')) {
return 'Insomnia';
} else {
return null;
}
}
String? getOS(String userAgent) {
if (userAgent.contains('Win')) {
return 'Windows';
} else if (userAgent.contains('Android')) {
return 'Android';
} else if (userAgent.contains('Macintosh')) {
return 'macOS';
} else if (userAgent.contains('iPhone') || userAgent.contains('iPad') || userAgent.contains('iPod')) {
return 'iOS';
} else if (userAgent.contains('X11')) {
return 'Linux';
} else {
return null;
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/determine_image_type.dart | import 'dart:typed_data';
/// Returns the image type (PNG, JPEG, GIF, etc) of the given image data.
/// Usually based on the first few bytes of the image.
String determineImageType(Uint8List bytes) {
if (bytes.lengthInBytes >= 2) {
if (bytes[0] == 0xFF && bytes[1] == 0xD8) {
return 'jpeg';
}
if (bytes[0] == 0x89 && bytes[1] == 0x50) {
return 'png';
}
if (bytes[0] == 0x47 && bytes[1] == 0x49) {
return 'gif';
}
if (bytes[0] == 0x42 && bytes[1] == 0x4D) {
return 'bmp';
}
}
return 'png';
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/api_route_builder.dart | import 'package:common/common.dart';
const _basePath = '/api/localsend';
/// Type-safe API paths
enum ApiRoute {
info('info'),
register('register'),
prepareUpload('prepare-upload', 'send-request'),
upload('upload', 'send'),
cancel('cancel'),
show('show'),
prepareDownload('prepare-download'),
download('download'),
;
const ApiRoute(String path, [String? legacy])
: v1 = '$_basePath/v1/${legacy ?? path}',
v2 = '$_basePath/v2/$path';
/// The server url for v1
final String v1;
/// The server url for v2
final String v2;
/// The client url
String target(Device target, {Map<String, String>? query}) {
final protocol = target.https ? 'https' : 'http';
final route = target.version == '1.0' ? v1 : v2;
if (query != null) {
return '$protocol://${target.ip}:${target.port}$route?${query.entries.map((e) => '${e.key}=${e.value}').join('&')}';
} else {
return '$protocol://${target.ip}:${target.port}$route';
}
}
/// The client url for polling
String targetRaw(String ip, int port, bool https, String version) {
final protocol = https ? 'https' : 'http';
final route = version == '1.0' ? v1 : v2;
return '$protocol://$ip:$port$route';
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/security_helper.dart | import 'dart:convert';
import 'dart:typed_data';
import 'package:basic_utils/basic_utils.dart';
import 'package:common/common.dart';
/// Generates a random [SecurityContextResult].
StoredSecurityContext generateSecurityContext([AsymmetricKeyPair? keyPair]) {
keyPair ??= CryptoUtils.generateRSAKeyPair();
final privateKey = keyPair.privateKey as RSAPrivateKey;
final publicKey = keyPair.publicKey as RSAPublicKey;
final dn = {
'CN': 'LocalSend User',
'O': '',
'OU': '',
'L': '',
'S': '',
'C': '',
};
final csr = X509Utils.generateRsaCsrPem(dn, privateKey, publicKey);
final certificate = X509Utils.generateSelfSignedCertificate(keyPair.privateKey, csr, 365 * 10);
final hash = calculateHashOfCertificate(certificate);
return StoredSecurityContext(
privateKey: CryptoUtils.encodeRSAPrivateKeyToPemPkcs1(privateKey),
publicKey: CryptoUtils.encodeRSAPublicKeyToPemPkcs1(publicKey),
certificate: certificate,
certificateHash: hash,
);
}
/// Calculates the hash of a certificate.
String calculateHashOfCertificate(String certificate) {
// Convert PEM to DER
final pemContent = certificate.replaceAll('\r\n', '\n').split('\n').where((line) => line.isNotEmpty && !line.startsWith('---')).join();
final der = base64Decode(pemContent);
// Calculate hash
return CryptoUtils.getHash(
Uint8List.fromList(der),
algorithmName: 'SHA-256',
);
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/util/file_path_helper.dart | import 'package:common/common.dart';
/// Matches myFile-123 -> 123
final _fileNumberRegex = RegExp(r'^(.*)(?:-(\d+))$');
extension FilePathStringExt on String {
String get extension {
final index = lastIndexOf('.');
if (index != -1) {
return substring(index + 1).toLowerCase();
} else {
return '';
}
}
String get fileName {
return replaceAll('\\', '/').split('/').last;
}
String withFileNameKeepExtension(String fileNameWithoutExt) {
return '$fileNameWithoutExt.$extension';
}
String withExtension(String ext) {
if (ext == '') {
return this;
} else {
return '$this.$ext';
}
}
String withCount(int count) {
final index = lastIndexOf('.');
final String fileName;
final String extension;
if (index != -1) {
fileName = substring(0, index);
extension = substring(index + 1).toLowerCase();
} else {
fileName = this;
extension = '';
}
final match = _fileNumberRegex.firstMatch(fileName);
if (match != null) {
return '${match.group(1)}-$count'.withExtension(extension);
} else {
return '$fileName-$count'.withExtension(extension);
}
}
FileType guessFileType() {
switch (extension) {
case 'bmp':
case 'jpg':
case 'jpeg':
case 'heic':
case 'png':
case 'gif':
case 'svg':
return FileType.image;
case 'mp4':
case 'mov':
return FileType.video;
case 'pdf':
return FileType.pdf;
case 'txt':
return FileType.text;
case 'apk':
return FileType.apk;
default:
return FileType.other;
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/open_file.dart | import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/dialogs/cannot_open_file_dialog.dart';
import 'package:open_filex/open_filex.dart';
import 'package:permission_handler/permission_handler.dart';
/// Opens the selected file which is stored on the device.
Future<void> openFile(
BuildContext context,
FileType fileType,
String filePath, {
void Function()? onDeleteTap,
}) async {
if ((fileType == FileType.apk || filePath.toLowerCase().endsWith('.apk')) && checkPlatform([TargetPlatform.android])) {
await Permission.requestInstallPackages.request();
}
final fileOpenResult = await OpenFilex.open(filePath);
if (fileOpenResult.type != ResultType.done && context.mounted) {
await CannotOpenFileDialog.open(context, filePath, onDeleteTap);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/directories.dart | import 'dart:io' show Directory, Platform;
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart' as path;
import 'package:shared_storage/shared_storage.dart' as shared_storage;
Future<String> getDefaultDestinationDirectory() async {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
// ignore: deprecated_member_use
final dir = await shared_storage.getExternalStoragePublicDirectory(shared_storage.EnvironmentDirectory.downloads);
return dir?.path ?? '/storage/emulated/0/Download';
case TargetPlatform.iOS:
return (await path.getApplicationDocumentsDirectory()).path;
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
case TargetPlatform.fuchsia:
var downloadDir = await path.getDownloadsDirectory();
if (downloadDir == null) {
if (defaultTargetPlatform == TargetPlatform.windows) {
downloadDir = Directory('${Platform.environment['HOMEPATH']}/Downloads');
if (!downloadDir.existsSync()) {
downloadDir = Directory(Platform.environment['HOMEPATH']!);
}
} else {
downloadDir = Directory('${Platform.environment['HOME']}/Downloads');
if (!downloadDir.existsSync()) {
downloadDir = Directory(Platform.environment['HOME']!);
}
}
}
return downloadDir.path.replaceAll('\\', '/');
}
}
Future<String> getCacheDirectory() async {
return (await path.getTemporaryDirectory()).path;
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/file_picker.dart | import 'dart:async';
import 'package:common/common.dart';
import 'package:file_picker/file_picker.dart' as file_picker;
import 'package:file_selector/file_selector.dart' as file_selector;
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/pages/apk_picker_page.dart';
import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/util/determine_image_type.dart';
import 'package:localsend_app/util/native/cross_file_converters.dart';
import 'package:localsend_app/util/native/pick_directory_path.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/util/sleep.dart';
import 'package:localsend_app/util/ui/asset_picker_translated_text_delegate.dart';
import 'package:localsend_app/widget/dialogs/loading_dialog.dart';
import 'package:localsend_app/widget/dialogs/message_input_dialog.dart';
import 'package:localsend_app/widget/dialogs/no_permission_dialog.dart';
import 'package:logging/logging.dart';
import 'package:pasteboard/pasteboard.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
final _logger = Logger('FilePickerHelper');
enum FilePickerOption {
file(Icons.description),
folder(Icons.folder),
media(Icons.image),
text(Icons.subject),
app(Icons.apps),
clipboard(Icons.paste);
const FilePickerOption(this.icon);
final IconData icon;
String get label {
switch (this) {
case FilePickerOption.file:
return t.sendTab.picker.file;
case FilePickerOption.folder:
return t.sendTab.picker.folder;
case FilePickerOption.media:
return t.sendTab.picker.media;
case FilePickerOption.text:
return t.sendTab.picker.text;
case FilePickerOption.app:
return t.sendTab.picker.app;
case FilePickerOption.clipboard:
return t.sendTab.picker.clipboard;
}
}
/// Returns the options for the current platform.
static List<FilePickerOption> getOptionsForPlatform() {
if (checkPlatform([TargetPlatform.iOS])) {
// On iOS, picking from media is most common.
// The file app is very limited.
return [
FilePickerOption.media,
FilePickerOption.text,
FilePickerOption.file,
FilePickerOption.folder,
];
} else if (checkPlatform([TargetPlatform.android])) {
// On android, the file app is most powerful.
// It actually also allows to pick media files.
return [
FilePickerOption.file,
FilePickerOption.media,
FilePickerOption.text,
FilePickerOption.folder,
FilePickerOption.app,
];
} else {
// Desktop
return [
FilePickerOption.file,
FilePickerOption.folder,
FilePickerOption.text,
FilePickerOption.clipboard,
];
}
}
}
class PickFileAction extends AsyncGlobalAction {
final FilePickerOption option;
final BuildContext context;
PickFileAction({
required this.option,
required this.context,
});
@override
Future<void> reduce() async {
switch (option) {
case FilePickerOption.file:
await _pickFiles(context, ref);
break;
case FilePickerOption.folder:
// ignore: use_build_context_synchronously
await _pickFolder(context, ref);
break;
case FilePickerOption.media:
// ignore: use_build_context_synchronously
await _pickMedia(context, ref);
break;
case FilePickerOption.text:
// ignore: use_build_context_synchronously
await _pickText(context, ref);
break;
case FilePickerOption.clipboard:
// ignore: use_build_context_synchronously
await _pickClipboard(context, ref);
break;
case FilePickerOption.app:
// ignore: use_build_context_synchronously
await _pickApp(context);
break;
}
}
@override
String toString() {
return 'PickAction(option: $option)';
}
}
Future<void> _pickFiles(BuildContext context, Ref ref) async {
if (checkPlatform([TargetPlatform.android])) {
// On android, the files are copied to the cache which takes some time.
// ignore: unawaited_futures
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => const LoadingDialog(),
);
}
try {
if (checkPlatform([TargetPlatform.android])) {
// We also need to use the file_picker package because file_selector does not expose the raw path.
final result = await file_picker.FilePicker.platform.pickFiles(allowMultiple: true);
if (result != null) {
await ref.redux(selectedSendingFilesProvider).dispatchAsync(AddFilesAction(
files: result.files,
converter: CrossFileConverters.convertPlatformFile,
));
}
} else {
final result = await file_selector.openFiles();
if (result.isNotEmpty) {
await ref.redux(selectedSendingFilesProvider).dispatchAsync(AddFilesAction(
files: result,
converter: CrossFileConverters.convertXFile,
));
}
}
} catch (e) {
// ignore: use_build_context_synchronously
await showDialog(context: context, builder: (_) => const NoPermissionDialog());
_logger.warning('Failed to pick files', e);
} finally {
// ignore: use_build_context_synchronously
Routerino.context.popUntilRoot(); // remove loading dialog
}
}
Future<void> _pickFolder(BuildContext context, Ref ref) async {
if (checkPlatform([TargetPlatform.android])) {
try {
await Permission.manageExternalStorage.request();
} catch (e) {
_logger.warning('Failed to request manageExternalStorage permission', e);
}
}
if (!context.mounted) {
return;
}
// ignore: unawaited_futures
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => const LoadingDialog(),
);
await sleepAsync(200); // Wait for the dialog to be shown
try {
final directoryPath = await pickDirectoryPath();
if (directoryPath != null) {
await ref.redux(selectedSendingFilesProvider).dispatchAsync(AddDirectoryAction(directoryPath));
}
} catch (e) {
_logger.warning('Failed to pick directory', e);
// ignore: use_build_context_synchronously
await showDialog(context: context, builder: (_) => const NoPermissionDialog());
} finally {
// ignore: use_build_context_synchronously
Routerino.context.popUntilRoot(); // remove loading dialog
}
}
Future<void> _pickMedia(BuildContext context, Ref ref) async {
final oldBrightness = Theme.of(context).brightness;
// ignore: use_build_context_synchronously
final List<AssetEntity>? result = await AssetPicker.pickAssets(
context,
pickerConfig: const AssetPickerConfig(maxAssets: 999, textDelegate: TranslatedAssetPickerTextDelegate()),
);
WidgetsBinding.instance.addPostFrameCallback((_) async {
// restore brightness for Android
await sleepAsync(500);
if (context.mounted) {
await updateSystemOverlayStyleWithBrightness(oldBrightness);
}
});
if (result != null) {
await ref.redux(selectedSendingFilesProvider).dispatchAsync(AddFilesAction(
files: result,
converter: CrossFileConverters.convertAssetEntity,
));
}
}
Future<void> _pickText(BuildContext context, Ref ref) async {
final result = await showDialog<String>(context: context, builder: (_) => const MessageInputDialog());
if (result != null) {
ref.redux(selectedSendingFilesProvider).dispatch(AddMessageAction(message: result));
}
}
Future<void> _pickClipboard(BuildContext context, Ref ref) async {
late List<String> files = [];
for (final file in await Pasteboard.files()) {
files.add(file);
}
if (files.isNotEmpty) {
await ref.redux(selectedSendingFilesProvider).dispatchAsync(AddFilesAction(
files: files.map((e) => XFile(e)).toList(),
converter: CrossFileConverters.convertXFile,
));
return;
}
final data = await Clipboard.getData(Clipboard.kTextPlain);
if (data?.text != null) {
ref.redux(selectedSendingFilesProvider).dispatch(AddMessageAction(message: data!.text!));
return;
}
final image = await Pasteboard.image;
if (image != null) {
final now = DateTime.now();
final fileName =
'clipboard_${now.year}-${now.month.twoDigitString}-${now.day.twoDigitString}_${now.hour.twoDigitString}-${now.minute.twoDigitString}.${determineImageType(image)}';
ref.redux(selectedSendingFilesProvider).dispatch(AddBinaryAction(
bytes: image,
fileType: FileType.image,
fileName: fileName,
));
return;
}
if (!context.mounted) {
return;
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(t.general.noItemInClipboard),
));
}
Future<void> _pickApp(BuildContext context) async {
// Currently, only Android APK
await context.push(() => const ApkPickerPage());
}
extension on int {
String get twoDigitString => toString().padLeft(2, '0');
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/pick_directory_path.dart | import 'package:file_picker/file_picker.dart';
import 'package:file_selector/file_selector.dart' as file_selector;
import 'package:flutter/material.dart';
import 'package:localsend_app/util/native/platform_check.dart';
/// Opens a file picker to select a directory.
/// Returns null if the user cancels the selection.
Future<String?> pickDirectoryPath() async {
if (checkPlatform([TargetPlatform.android, TargetPlatform.iOS])) {
/// We need to use the file_picker package because file_selector does not expose the raw path.
/// We need the raw path to properly manipulate the path to save new files, or
/// to list files recursively.
/// Also, on iOS, file_selector does not work with directories.
return await FilePicker.platform.getDirectoryPath();
} else {
return await file_selector.getDirectoryPath();
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/platform_check.dart | import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
bool checkPlatform(List<TargetPlatform> platforms, {bool web = false}) {
if (web && kIsWeb) {
return true;
}
return platforms.contains(defaultTargetPlatform);
}
bool checkPlatformIsNot(List<TargetPlatform> platforms, {bool web = false}) {
return !checkPlatform(platforms, web: web);
}
/// This platform runs on a "traditional" computer
bool checkPlatformIsDesktop() {
return checkPlatform([TargetPlatform.linux, TargetPlatform.windows, TargetPlatform.macOS]);
}
/// This platform supports tray
bool checkPlatformHasTray() {
return checkPlatform([TargetPlatform.windows, TargetPlatform.macOS, TargetPlatform.linux]);
}
/// This platform can receive share intents
bool checkPlatformCanReceiveShareIntent() {
return checkPlatform([TargetPlatform.android, TargetPlatform.iOS]);
}
/// This platform can select folders
bool checkPlatformWithFolderSelect() {
return checkPlatform([TargetPlatform.android, TargetPlatform.iOS, TargetPlatform.linux, TargetPlatform.windows, TargetPlatform.macOS]);
}
/// This platform has a gallery
bool checkPlatformWithGallery() {
return checkPlatform([TargetPlatform.android, TargetPlatform.iOS]);
}
/// This platform has access to file system
/// On android, do not allow to change
bool checkPlatformWithFileSystem() {
return checkPlatform([TargetPlatform.linux, TargetPlatform.windows, TargetPlatform.android, TargetPlatform.macOS]);
}
/// Convenience function to check if the app is not running on a Linux device with the Wayland display manager
bool checkPlatformIsNotWaylandDesktop() {
if (checkPlatform([TargetPlatform.linux])) {
if (Platform.environment['XDG_SESSION_TYPE'] == 'wayland') {
return false;
} else {
return true;
}
}
return true;
}
/// This platform supports payment (in-app purchase)
bool checkPlatformSupportPayment() {
return checkPlatform([TargetPlatform.android, TargetPlatform.iOS, TargetPlatform.macOS]);
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/cross_file_converters.dart | import 'dart:io';
import 'package:common/common.dart';
import 'package:device_apps/device_apps.dart';
import 'package:file_picker/file_picker.dart' as file_picker;
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/util/file_path_helper.dart';
import 'package:share_handler/share_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
/// Utility functions to convert third party models to common [CrossFile] model.
class CrossFileConverters {
static Future<CrossFile> convertPlatformFile(file_picker.PlatformFile file) async {
return CrossFile(
name: file.name,
fileType: file.name.guessFileType(),
size: file.size,
thumbnail: null,
asset: null,
path: kIsWeb ? null : file.path,
bytes: kIsWeb ? file.bytes! : null,
);
}
static Future<CrossFile> convertAssetEntity(AssetEntity asset) async {
final file = (await asset.originFile)!;
return CrossFile(
name: await asset.titleAsync,
fileType: asset.type == AssetType.video ? FileType.video : FileType.image,
size: await file.length(),
thumbnail: null,
asset: asset,
path: file.path,
bytes: null,
);
}
static Future<CrossFile> convertXFile(XFile file) async {
return CrossFile(
name: file.name,
fileType: file.name.guessFileType(),
size: await file.length(),
thumbnail: null,
asset: null,
path: kIsWeb ? null : file.path,
bytes: kIsWeb ? await file.readAsBytes() : null, // we can fetch it now because in Web it is already there
);
}
static Future<CrossFile> convertSharedAttachment(SharedAttachment attachment) async {
final file = File(attachment.path);
final fileName = attachment.path.fileName;
return CrossFile(
name: fileName,
fileType: fileName.guessFileType(),
size: await file.length(),
thumbnail: null,
asset: null,
path: file.path,
bytes: null,
);
}
static Future<CrossFile> convertApplication(Application app) async {
final file = File(app.apkFilePath);
return CrossFile(
name: '${app.appName.trim()} - v${app.versionName}.apk',
fileType: FileType.apk,
thumbnail: app is ApplicationWithIcon ? app.icon : null,
size: await file.length(),
asset: null,
path: app.apkFilePath,
bytes: null,
);
}
}
extension CompareFile on CrossFile {
bool isSameFile({required CrossFile otherFile}) {
return (path ?? '') == (otherFile.path ?? '');
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/file_saver.dart | import 'dart:io';
import 'dart:typed_data';
import 'package:gal/gal.dart';
import 'package:localsend_app/util/file_path_helper.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:saf_stream/saf_stream.dart';
final _logger = Logger('FileSaver');
final _saf = SafStream();
/// Saves the data [stream] to the [destinationPath].
/// [onProgress] will be called on every 100 ms.
Future<void> saveFile({
required String destinationPath,
required String name,
required bool saveToGallery,
required bool isImage,
required Stream<List<int>> stream,
required int? androidSdkInt,
required void Function(int savedBytes) onProgress,
}) async {
if (!saveToGallery && androidSdkInt != null && androidSdkInt <= 29) {
final sdCardPath = getSdCardPath(destinationPath);
if (sdCardPath != null) {
// Use Android SAF to save the file to the SD card
final info = await _saf.startWriteStream(
Uri.parse('content://com.android.externalstorage.documents/tree/${sdCardPath.sdCardId}:${sdCardPath.path}'),
name,
isImage ? 'image/*' : '*/*',
);
final sessionID = info.session;
await _saveFile(
destinationPath: destinationPath,
saveToGallery: saveToGallery,
isImage: isImage,
stream: stream,
onProgress: onProgress,
write: null,
writeAsync: (data) async {
await _saf.writeChunk(sessionID, Uint8List.fromList(data));
},
close: () async {
await _saf.endWriteStream(sessionID);
},
);
return;
}
}
final sink = File(destinationPath).openWrite();
await _saveFile(
destinationPath: destinationPath,
saveToGallery: saveToGallery,
isImage: isImage,
stream: stream,
onProgress: onProgress,
write: sink.add,
writeAsync: null,
close: sink.close,
);
}
Future<void> _saveFile({
required String destinationPath,
required bool saveToGallery,
required bool isImage,
required Stream<List<int>> stream,
required void Function(int savedBytes) onProgress,
required void Function(List<int> data)? write,
required Future<void> Function(List<int> data)? writeAsync,
required Future<void> Function() close,
}) async {
try {
int savedBytes = 0;
final stopwatch = Stopwatch()..start();
await for (final event in stream) {
if (writeAsync != null) {
await writeAsync(event);
} else {
write!(event);
}
savedBytes += event.length;
if (stopwatch.elapsedMilliseconds >= 100) {
stopwatch.reset();
onProgress(savedBytes);
}
}
await close();
if (saveToGallery) {
isImage ? await Gal.putImage(destinationPath) : await Gal.putVideo(destinationPath);
await File(destinationPath).delete();
}
onProgress(savedBytes); // always emit final event
} catch (_) {
try {
await close();
await File(destinationPath).delete();
} catch (e) {
_logger.warning('Could not delete file', e);
}
rethrow;
}
}
/// If there is a file with the same name, then it appends a number to its file name
Future<String> digestFilePathAndPrepareDirectory({required String parentDirectory, required String fileName}) async {
final actualFileName = p.basename(fileName);
final fileNameParts = p.split(fileName);
final dir = p.joinAll([parentDirectory, ...fileNameParts.take(fileNameParts.length - 1)]);
Directory(dir).createSync(recursive: true);
String destinationPath;
int counter = 1;
do {
destinationPath = counter == 1 ? p.join(dir, actualFileName) : p.join(dir, actualFileName.withCount(counter));
counter++;
} while (await File(destinationPath).exists());
return destinationPath;
}
final _sdCardPathRegex = RegExp(r'^/storage/([A-Fa-f0-9]{4}-[A-Fa-f0-9]{4})/(.*)$');
class SdCardPath {
final String sdCardId;
final String path;
SdCardPath(this.sdCardId, this.path);
}
/// Checks if the [path] is on the SD card and returns the SD card path.
/// Returns `null` if the [path] is not on the SD card.
/// Only works on Android.
SdCardPath? getSdCardPath(String path) {
final match = _sdCardPathRegex.firstMatch(path);
if (match == null) {
return null;
}
return SdCardPath(match.group(1)!, match.group(2)!);
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/cache_helper.dart | // ignore_for_file: discarded_futures, unawaited_futures
import 'dart:io';
import 'dart:isolate';
import 'package:app_group_directory/app_group_directory.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:localsend_app/util/file_path_helper.dart';
import 'package:localsend_app/util/logger.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:logging/logging.dart';
import 'package:path_provider/path_provider.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
final _logger = Logger('ClearCacheAction');
/// Clears the cache.
/// It runs on a separate isolate to avoid blocking the UI.
class ClearCacheAction extends AsyncGlobalAction {
@override
Future<void> reduce() async {
// The token statement must be outside the lambda because it must be executed on the root isolate.
final token = ServicesBinding.rootIsolateToken!;
await Isolate.run(() => _clear(token));
}
}
Future<void> _clear(RootIsolateToken token) async {
initLogger(Level.ALL);
BackgroundIsolateBinaryMessenger.ensureInitialized(token);
final futures = (
FilePicker.platform.clearTemporaryFiles(),
PhotoManager.clearFileCache(),
checkPlatform([TargetPlatform.iOS, TargetPlatform.android])
? getTemporaryDirectory().then((cacheDir) {
cacheDir.list().listen((event) {
if (event is File) {
event.delete().then((_) {}).catchError((error) {
_logger.warning('Failed to delete file: $error');
});
}
});
})
: Future.value(),
checkPlatform([TargetPlatform.iOS])
? AppGroupDirectory.getAppGroupDirectory('group.org.localsend.localsendApp').then((directory) async {
if (directory == null) {
_logger.warning('Failed to get app group directory');
return;
}
// delete contents of the directory (only files, not directories)
await for (final entry in directory.list(recursive: false, followLinks: false)) {
if (entry is File && !entry.path.fileName.startsWith('.')) {
_logger.info('Deleting ${entry.path}');
entry.deleteSync();
}
}
})
: Future.value(),
).wait;
try {
await futures;
} catch (e) {
_logger.warning('Failed to clear cache: $e');
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/cmd_helper.dart | import 'dart:io';
import 'package:logging/logging.dart';
final _logger = Logger('CmdHelper');
/// Runs [commands] in cmd having admin privileges.
Future<void> runWindowsCommandAsAdmin(List<String> commands) async {
try {
final joinedCommands = commands.join(' & ');
await Process.run(
'powershell',
[
'-Command',
"Start-Process -Verb RunAs cmd.exe -Args '/c', '$joinedCommands & echo. & pause'",
],
);
} catch (e) {
_logger.warning('Could not run command as admin', e);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/tray_helper.dart | import 'package:flutter/foundation.dart';
import 'package:localsend_app/gen/assets.gen.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/provider/animation_provider.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:tray_manager/tray_manager.dart' as tm;
import 'package:window_manager/window_manager.dart';
final _logger = Logger('TrayHelper');
enum TrayEntry {
open,
close,
}
Future<void> initTray() async {
if (!checkPlatformHasTray()) {
return;
}
try {
if (checkPlatform([TargetPlatform.windows])) {
await tm.trayManager.setIcon(Assets.img.logo);
} else if (checkPlatform([TargetPlatform.macOS])) {
await tm.trayManager.setIcon(Assets.img.logo32Black.path, isTemplate: true);
} else if (checkPlatform([TargetPlatform.linux])) {
await tm.trayManager.setIcon(Assets.img.logo32White.path);
} else {
await tm.trayManager.setIcon(Assets.img.logo32.path);
}
final items = [
tm.MenuItem(
key: TrayEntry.open.name,
label: t.tray.open,
),
tm.MenuItem(
key: TrayEntry.close.name,
label: t.tray.close,
),
];
await tm.trayManager.setContextMenu(tm.Menu(items: items));
// No Linux implementation for setToolTip available as of tray_manager 0.2.2
// https://pub.dev/packages/tray_manager#api
if (!checkPlatform([TargetPlatform.linux])) {
await tm.trayManager.setToolTip(t.appName);
}
} catch (e) {
_logger.warning('Failed to init tray', e);
}
}
Future<void> hideToTray() async {
await windowManager.hide();
if (checkPlatform([TargetPlatform.macOS])) {
// This will crash on Windows
// https://github.com/localsend/localsend/issues/32
await windowManager.setSkipTaskbar(true);
}
// Disable animations
RefenaScope.defaultRef.notifier(sleepProvider).setState((_) => true);
}
Future<void> showFromTray() async {
await windowManager.show();
await windowManager.focus();
if (checkPlatform([TargetPlatform.macOS])) {
// This will crash on Windows
// https://github.com/localsend/localsend/issues/32
await windowManager.setSkipTaskbar(false);
}
// Enable animations
RefenaScope.defaultRef.notifier(sleepProvider).setState((_) => false);
}
Future<void> destroyTray() async {
if (!checkPlatform([TargetPlatform.linux])) {
await tm.trayManager.destroy();
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/open_folder.dart | import 'package:logging/logging.dart';
import 'package:open_filex/open_filex.dart';
final _logger = Logger('OpenFolder');
/// Opens the selected file which is stored on the device.
Future<void> openFolder(String path) async {
if (!path.endsWith('/')) {
path = '$path/';
}
final result = await OpenFilex.open(path);
_logger.info('Open folder result: ${result.message}, path: $path');
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/device_info_helper.dart | import 'package:common/common.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:slang/builder/model/enums.dart';
import 'package:slang/builder/utils/string_extensions.dart';
class DeviceInfoResult {
final DeviceType deviceType;
final String? deviceModel;
// Used to properly set Edge-to-Edge mode on Android
// See https://github.com/flutter/flutter/issues/90098
final int? androidSdkInt;
DeviceInfoResult({
required this.deviceType,
required this.deviceModel,
required this.androidSdkInt,
});
}
Future<DeviceInfoResult> getDeviceInfo() async {
final plugin = DeviceInfoPlugin();
final DeviceType deviceType;
final String? deviceModel;
int? androidSdkInt;
if (kIsWeb) {
deviceType = DeviceType.web;
final deviceInfo = await plugin.webBrowserInfo;
deviceModel = deviceInfo.browserName.humanName;
} else {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.iOS:
deviceType = DeviceType.mobile;
break;
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
case TargetPlatform.fuchsia:
deviceType = DeviceType.desktop;
break;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
final deviceInfo = await plugin.androidInfo;
deviceModel = deviceInfo.brand.toCase(CaseStyle.pascal);
androidSdkInt = deviceInfo.version.sdkInt;
break;
case TargetPlatform.iOS:
final deviceInfo = await plugin.iosInfo;
deviceModel = deviceInfo.localizedModel;
break;
case TargetPlatform.linux:
deviceModel = 'Linux';
break;
case TargetPlatform.macOS:
deviceModel = 'macOS';
break;
case TargetPlatform.windows:
deviceModel = 'Windows';
break;
case TargetPlatform.fuchsia:
deviceModel = 'Fuchsia';
break;
}
}
return DeviceInfoResult(
deviceType: deviceType,
deviceModel: deviceModel,
androidSdkInt: androidSdkInt,
);
}
extension on BrowserName {
String? get humanName {
switch (this) {
case BrowserName.firefox:
return 'Firefox';
case BrowserName.samsungInternet:
return 'Samsung Internet';
case BrowserName.opera:
return 'Opera';
case BrowserName.msie:
return 'Internet Explorer';
case BrowserName.edge:
return 'Microsoft Edge';
case BrowserName.chrome:
return 'Google Chrome';
case BrowserName.safari:
return 'Safari';
case BrowserName.unknown:
return null;
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/taskbar_helper.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:macos_dock_progress/macos_dock_progress.dart';
import 'package:windows_taskbar/windows_taskbar.dart';
class TaskbarHelper {
static final _isWindows = checkPlatform([TargetPlatform.windows]);
static final _isMacos = checkPlatform([TargetPlatform.macOS]);
static Future<void> clearProgressBar() async {
if (_isWindows) {
await WindowsTaskbar.setProgressMode(TaskbarProgressMode.noProgress);
} else if (_isMacos) {
await DockProgress.setProgress(1.0);
}
}
static Future<void> setProgressBar(int progress, int total) async {
if (total != double.minPositive.toInt() && total != double.maxFinite.toInt()) {
if (_isWindows) {
await WindowsTaskbar.setProgress(progress, total);
} else if (_isMacos) {
await DockProgress.setProgress(double.parse((progress / total).toStringAsFixed(3)));
}
} else {
if (_isWindows) {
await WindowsTaskbar.setProgressMode(TaskbarProgressMode.indeterminate);
}
}
}
static Future<void> setProgressBarMode(int mode) async {
if (_isWindows) {
await WindowsTaskbar.setProgressMode(mode);
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/native/autostart_helper.dart | import 'dart:io';
import 'package:launch_at_startup/launch_at_startup.dart';
import 'package:localsend_app/init.dart';
import 'package:localsend_app/model/state/settings_state.dart';
import 'package:logging/logging.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
final _logger = Logger('AutoStartHelper');
/// Currently, only works for windows
Future<bool> initEnableAutoStartAndOpenSettings(SettingsState settings, [bool? isWindows]) async {
try {
// In case somebody don't use msix
final packageInfo = await PackageInfo.fromPlatform();
launchAtStartup.setup(
appName: packageInfo.appName,
appPath: Platform.resolvedExecutable,
args: [if (!settings.autoStartLaunchMinimized) launchAtStartupArg],
);
// We just add this entry so we have the same behaviour like in msix
if (!(await launchAtStartup.isEnabled())) {
final result = await launchAtStartup.enable();
return result;
}
} catch (e) {
_logger.warning('Could not init auto start', e);
return false;
}
// Can be linux on startup flag change
if (isWindows ?? false) {
try {
// Ideally, we should configure it programmatically
// The launch_at_startup package does not support this currently
// See: https://learn.microsoft.com/en-us/uwp/api/Windows.ApplicationModel.StartupTask?view=winrt-22621
await launchUrl(Uri.parse('ms-settings:startupapps'));
} catch (e) {
_logger.warning('Could not open startup settings', e);
}
}
return false;
}
Future<bool> initDisableAutoStart(SettingsState settings) async {
try {
// In case somebody don't use msix
final packageInfo = await PackageInfo.fromPlatform();
launchAtStartup.setup(
appName: packageInfo.appName,
appPath: Platform.resolvedExecutable,
args: [if (settings.autoStartLaunchMinimized) launchAtStartupArg],
);
// We just add this entry so we have the same behaviour like in msix
if (await launchAtStartup.isEnabled()) {
final result = await launchAtStartup.disable();
return result;
}
} catch (e) {
_logger.warning('Could not init auto start', e);
return false;
}
return false;
}
Future<bool> isLinuxLaunchAtStartEnabled() async {
final packageInfo = await PackageInfo.fromPlatform();
File desktopFile = File('${Platform.environment['HOME']}/.config/autostart/${packageInfo.appName}.desktop');
return desktopFile.existsSync();
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/ui/asset_picker_translated_text_delegate.dart | import 'package:localsend_app/gen/strings.g.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
class TranslatedAssetPickerTextDelegate extends AssetPickerTextDelegate {
const TranslatedAssetPickerTextDelegate();
@override
String get languageCode => LocaleSettings.currentLocale.languageCode;
@override
String get confirm => t.assetPicker.confirm;
@override
String get cancel => t.assetPicker.cancel;
@override
String get edit => t.assetPicker.edit;
@override
String get gifIndicator => t.assetPicker.gifIndicator;
@override
String get loadFailed => t.assetPicker.loadFailed;
@override
String get original => t.assetPicker.original;
@override
String get preview => t.assetPicker.preview;
@override
String get select => t.assetPicker.select;
@override
String get emptyList => t.assetPicker.emptyList;
@override
String get unSupportedAssetType => t.assetPicker.unSupportedAssetType;
@override
String get unableToAccessAll => t.assetPicker.unableToAccessAll;
@override
String get viewingLimitedAssetsTip => t.assetPicker.viewingLimitedAssetsTip;
@override
String get changeAccessibleLimitedAssets => t.assetPicker.changeAccessibleLimitedAssets;
@override
String get accessAllTip => t.assetPicker.accessAllTip;
@override
String get goToSystemSettings => t.assetPicker.goToSystemSettings;
@override
String get accessLimitedAssets => t.assetPicker.accessLimitedAssets;
@override
String get accessiblePathName => t.assetPicker.accessiblePathName;
@override
String get sTypeAudioLabel => t.assetPicker.sTypeAudioLabel;
@override
String get sTypeImageLabel => t.assetPicker.sTypeImageLabel;
@override
String get sTypeVideoLabel => t.assetPicker.sTypeVideoLabel;
@override
String get sTypeOtherLabel => t.assetPicker.sTypeOtherLabel;
@override
String get sActionPlayHint => t.assetPicker.sActionPlayHint;
@override
String get sActionPreviewHint => t.assetPicker.sActionPreviewHint;
@override
String get sActionSelectHint => t.assetPicker.sActionSelectHint;
@override
String get sActionSwitchPathLabel => t.assetPicker.sActionSwitchPathLabel;
@override
String get sActionUseCameraHint => t.assetPicker.sActionUseCameraHint;
@override
String get sNameDurationLabel => t.assetPicker.sNameDurationLabel;
@override
String get sUnitAssetCountLabel => t.assetPicker.sUnitAssetCountLabel;
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/ui/snackbar.dart | import 'package:flutter/material.dart';
extension SnackbarExt on BuildContext {
void showSnackBar(String text) {
final scaffold = ScaffoldMessenger.of(this);
scaffold.removeCurrentSnackBar();
scaffold.showSnackBar(
SnackBar(
content: Text(text),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/ui/dynamic_colors.dart | import 'package:dynamic_color/dynamic_color.dart';
import 'package:flutter/material.dart';
import 'package:refena_flutter/refena_flutter.dart';
class DynamicColors {
final ColorScheme light;
final ColorScheme dark;
const DynamicColors({
required this.light,
required this.dark,
});
}
final dynamicColorsProvider = Provider<DynamicColors?>((ref) => throw 'not initialized');
/// Returns the dynamic colors.
/// A copy of the dynamic_color_plugin implementation to retrieve the dynamic colors without a widget.
/// We need to replace [PlatformException] with a generic exception because on Windows 7 it is somehow not a [PlatformException].
Future<DynamicColors?> getDynamicColors() async {
try {
final corePalette = await DynamicColorPlugin.getCorePalette();
if (corePalette != null) {
debugPrint('dynamic_color: Core palette detected.');
return DynamicColors(
light: corePalette.toColorScheme(),
dark: corePalette.toColorScheme(brightness: Brightness.dark),
);
}
} catch (e) {
debugPrint('dynamic_color: Failed to obtain core palette.');
}
try {
final accentColor = await DynamicColorPlugin.getAccentColor();
if (accentColor != null) {
debugPrint('dynamic_color: Accent color detected.');
return DynamicColors(
light: ColorScheme.fromSeed(
seedColor: accentColor,
brightness: Brightness.light,
),
dark: ColorScheme.fromSeed(
seedColor: accentColor,
brightness: Brightness.dark,
),
);
}
} catch (e) {
debugPrint('dynamic_color: Failed to obtain accent color.');
}
return null;
}
| 0 |
mirrored_repositories/localsend/app/lib/util | mirrored_repositories/localsend/app/lib/util/ui/nav_bar_padding.dart | import 'package:flutter/material.dart';
/// Since we use edge-to-edge mode on Android, the widgets may be hidden behind the navigation bar.
double getNavBarPadding(BuildContext context) {
return MediaQuery.of(context).padding.bottom;
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/copyable_text.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:localsend_app/util/ui/snackbar.dart';
class CopyableText extends StatelessWidget {
final TextSpan? prefix;
final String name;
final String? value;
const CopyableText({
this.prefix,
required this.name,
required this.value,
});
@override
Widget build(BuildContext context) {
return InkWell(
onTap: value == null
? null
: () async {
await Clipboard.setData(ClipboardData(text: value!));
if (context.mounted) {
context.showSnackBar('Copied $name to clipboard!');
}
},
child: Text.rich(
TextSpan(
children: [
if (prefix != null) prefix!,
TextSpan(text: value ?? '-'),
],
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/labeled_checkbox.dart | import 'package:flutter/material.dart';
class LabeledCheckbox extends StatelessWidget {
final String label;
final bool value;
final ValueChanged<bool?> onChanged;
final bool labelFirst;
const LabeledCheckbox({
required this.label,
required this.value,
required this.onChanged,
this.labelFirst = false,
});
@override
Widget build(BuildContext context) {
return Row(
children: labelFirst
? [
Text(label),
const SizedBox(width: 5),
Checkbox(
value: value,
onChanged: onChanged,
),
]
: [
Checkbox(
value: value,
onChanged: onChanged,
),
const SizedBox(width: 5),
Text(label),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/file_thumbnail.dart | import 'dart:io';
import 'dart:typed_data';
import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/util/file_type_ext.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
const double defaultThumbnailSize = 50;
class SmartFileThumbnail extends StatelessWidget {
final Uint8List? bytes;
final AssetEntity? asset;
final String? path;
final FileType fileType;
const SmartFileThumbnail({
required this.bytes,
required this.asset,
required this.path,
required this.fileType,
});
factory SmartFileThumbnail.fromCrossFile(CrossFile file) {
return SmartFileThumbnail(
bytes: file.thumbnail,
asset: file.asset,
path: file.path,
fileType: file.fileType,
);
}
@override
Widget build(BuildContext context) {
if (bytes != null) {
return MemoryThumbnail(
bytes: bytes,
fileType: fileType,
);
} else if (asset != null) {
return AssetThumbnail(
asset: asset!,
fileType: fileType,
);
} else {
return FilePathThumbnail(
path: path,
fileType: fileType,
);
}
}
}
class AssetThumbnail extends StatelessWidget {
final AssetEntity asset;
final FileType fileType;
const AssetThumbnail({
required this.asset,
required this.fileType,
});
@override
Widget build(BuildContext context) {
return _Thumbnail(
thumbnail: AssetEntityImage(
asset,
isOriginal: false,
thumbnailSize: const ThumbnailSize.square(64),
thumbnailFormat: ThumbnailFormat.jpeg,
),
icon: fileType.icon,
);
}
}
class FilePathThumbnail extends StatelessWidget {
final String? path;
final FileType fileType;
const FilePathThumbnail({
required this.path,
required this.fileType,
});
@override
Widget build(BuildContext context) {
final Widget? thumbnail;
if (path != null && fileType == FileType.image) {
thumbnail = Image.file(
File(path!),
cacheWidth: 64, // reduce memory with low cached size; do not set cacheHeight because the image must keep its ratio
errorBuilder: (_, __, ___) => Padding(
padding: const EdgeInsets.all(10),
child: Icon(fileType.icon, size: 32),
),
);
} else {
thumbnail = null;
}
return _Thumbnail(
thumbnail: thumbnail,
icon: fileType.icon,
);
}
}
class MemoryThumbnail extends StatelessWidget {
final Uint8List? bytes;
final FileType fileType;
final double size;
const MemoryThumbnail({
required this.bytes,
required this.fileType,
this.size = defaultThumbnailSize,
});
@override
Widget build(BuildContext context) {
final Widget? thumbnail;
if (bytes != null) {
thumbnail = Padding(
padding: fileType == FileType.apk ? const EdgeInsets.all(50) : EdgeInsets.zero,
child: Image.memory(
bytes!,
errorBuilder: (_, __, ___) => Padding(
padding: const EdgeInsets.all(10),
child: Icon(fileType.icon, size: 32),
),
),
);
} else {
thumbnail = null;
}
return _Thumbnail(
thumbnail: thumbnail,
icon: fileType.icon,
size: size,
);
}
}
class _Thumbnail extends StatelessWidget {
final Widget? thumbnail;
final IconData? icon;
final double size;
const _Thumbnail({
required this.thumbnail,
required this.icon,
this.size = defaultThumbnailSize,
});
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: ColoredBox(
color: Theme.of(context).inputDecorationTheme.fillColor!,
child: thumbnail == null
? Icon(icon!, size: 32)
: FittedBox(
fit: BoxFit.cover,
clipBehavior: Clip.hardEdge,
child: thumbnail,
),
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/responsive_list_view.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/util/ui/nav_bar_padding.dart';
import 'package:localsend_app/widget/responsive_builder.dart';
class ResponsiveListView extends StatelessWidget {
static const defaultMaxWidth = 600.0;
final double maxWidth;
final ScrollController? controller;
final EdgeInsets padding;
final EdgeInsets desktopPadding;
final List<Widget>? children;
final Widget? child;
const ResponsiveListView.single({
this.maxWidth = defaultMaxWidth,
this.controller,
required this.padding,
EdgeInsets? tabletPadding,
required Widget this.child,
super.key,
}) : desktopPadding = tabletPadding ?? const EdgeInsets.symmetric(horizontal: 10, vertical: 30),
children = null;
const ResponsiveListView({
this.maxWidth = defaultMaxWidth,
this.controller,
required this.padding,
EdgeInsets? tabletPadding,
required List<Widget> this.children,
super.key,
}) : desktopPadding = tabletPadding ?? const EdgeInsets.symmetric(horizontal: 10, vertical: 30),
child = null;
@override
Widget build(BuildContext context) {
if (children != null) {
return SingleChildScrollView(
controller: controller,
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxWidth),
child: ResponsiveBuilder(
builder: (sizingInformation) {
final bottom = sizingInformation.isDesktop ? desktopPadding.bottom : padding.bottom;
return Padding(
padding: (sizingInformation.isDesktop ? desktopPadding : padding).copyWith(
bottom: bottom + getNavBarPadding(context),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children!,
),
);
},
),
),
),
);
} else {
return Center(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxWidth),
child: ResponsiveBuilder(
builder: (sizingInformation) {
return Padding(
padding: sizingInformation.isDesktop ? desktopPadding : padding,
child: child!,
);
},
),
),
);
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/device_bage.dart | import 'package:flutter/material.dart';
class DeviceBadge extends StatelessWidget {
final Color backgroundColor;
final Color foregroundColor;
final String label;
const DeviceBadge({
required this.backgroundColor,
required this.foregroundColor,
required this.label,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(5),
),
child: Text(label, style: TextStyle(color: foregroundColor)),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/opacity_slideshow.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:localsend_app/util/sleep.dart';
/// A slideshow of widgets using [AnimatedOpacity] as transition.
class OpacitySlideshow extends StatefulWidget {
final List<Widget> children;
final int durationMillis;
final int switchDurationMillis;
final bool running;
const OpacitySlideshow({
required this.children,
required this.durationMillis,
this.switchDurationMillis = 300,
this.running = true,
super.key,
});
@override
State<OpacitySlideshow> createState() => _OpacitySlideshowState();
}
class _OpacitySlideshowState extends State<OpacitySlideshow> {
Timer? _timer;
int _index = 0;
double _opacity = 1;
@override
void initState() {
super.initState();
_startTimer();
}
@override
void dispose() {
super.dispose();
_timer?.cancel();
}
@override
void didUpdateWidget(OpacitySlideshow oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.running && !widget.running) {
_timer?.cancel();
} else if (!oldWidget.running && widget.running) {
_startTimer();
}
}
void _startTimer() {
if (widget.children.length <= 1) {
return;
}
_timer = Timer.periodic(Duration(milliseconds: widget.durationMillis), (_) async {
if (!mounted) return;
setState(() {
_opacity = 0;
});
await sleepAsync(widget.switchDurationMillis);
if (!mounted) return;
setState(() {
_index = (_index + 1) % widget.children.length;
_opacity = 1;
});
});
}
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
opacity: _opacity,
duration: Duration(milliseconds: widget.switchDurationMillis),
child: widget.children[_index],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/responsive_builder.dart | import 'package:flutter/material.dart';
class SizingInformation {
final bool isMobile;
final bool isTabletOrDesktop;
final bool isDesktop;
const SizingInformation(double width)
: isMobile = width < 700,
isTabletOrDesktop = width >= 700,
isDesktop = width >= 800;
}
class ResponsiveBuilder extends StatelessWidget {
final Widget Function(SizingInformation sizingInformation) builder;
const ResponsiveBuilder({required this.builder});
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return builder(SizingInformation(width));
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/custom_progress_bar.dart | import 'package:flutter/material.dart';
class CustomProgressBar extends StatelessWidget {
final double? progress;
final double borderRadius;
final Color? color;
const CustomProgressBar({required this.progress, this.borderRadius = 10, this.color});
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(borderRadius),
child: LinearProgressIndicator(
value: progress,
color: color ?? Theme.of(context).colorScheme.primary,
minHeight: 10,
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/debug_entry.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/widget/copyable_text.dart';
class DebugEntry extends StatelessWidget {
static const headerStyle = TextStyle(fontWeight: FontWeight.bold);
final String name;
final String? value;
const DebugEntry({
required this.name,
required this.value,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 20),
Text(name, style: headerStyle),
CopyableText(
name: name,
value: value,
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/big_button.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/widget/responsive_builder.dart';
class BigButton extends StatelessWidget {
final IconData icon;
final String label;
final bool filled;
final VoidCallback onTap;
const BigButton({
required this.icon,
required this.label,
required this.filled,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final sizingInformation = SizingInformation(MediaQuery.sizeOf(context).width);
final buttonWidth = sizingInformation.isDesktop ? 100.0 : 90.0;
const buttonHeight = 65.0;
return ConstrainedBox(
constraints: BoxConstraints(
maxWidth: buttonWidth,
minWidth: buttonWidth,
minHeight: buttonHeight,
maxHeight: buttonHeight,
),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: filled ? colorScheme.primary : colorScheme.secondaryContainerIfDark,
foregroundColor: filled ? colorScheme.onPrimary : colorScheme.onSecondaryContainerIfDark,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
padding: EdgeInsets.only(left: 2, right: 2, top: 10 + desktopPaddingFix, bottom: 8 + desktopPaddingFix),
),
onPressed: onTap,
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(icon),
FittedBox(
alignment: Alignment.bottomCenter,
child: Text(label, maxLines: 1),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/animated_opacity_cross_fade.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/util/sleep.dart';
/// The same as AnimatedCrossFade but with an opacity animation
class AnimatedOpacityCrossFade extends StatefulWidget {
final CrossFadeState crossFadeState;
final int durationMillis;
final Widget firstChild;
final Widget secondChild;
const AnimatedOpacityCrossFade({
required this.crossFadeState,
required this.durationMillis,
required this.firstChild,
required this.secondChild,
});
@override
State<AnimatedOpacityCrossFade> createState() => _AnimatedOpacityCrossFadeState();
}
class _AnimatedOpacityCrossFadeState extends State<AnimatedOpacityCrossFade> {
late CrossFadeState _internalState;
double _opacity = 1;
@override
void initState() {
super.initState();
_internalState = widget.crossFadeState;
}
@override
void didUpdateWidget(AnimatedOpacityCrossFade oldWidget) async {
super.didUpdateWidget(oldWidget);
if (oldWidget.crossFadeState != widget.crossFadeState) {
setState(() {
_opacity = 0;
});
final targetState = widget.crossFadeState;
await sleepAsync(widget.durationMillis);
if (mounted && targetState == widget.crossFadeState) {
setState(() {
_internalState = widget.crossFadeState;
_opacity = 1;
});
}
}
}
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
opacity: _opacity,
duration: Duration(milliseconds: widget.durationMillis ~/ 2),
child: _internalState == CrossFadeState.showFirst ? widget.firstChild : widget.secondChild,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/local_send_logo.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/assets.gen.dart';
class LocalSendLogo extends StatelessWidget {
final bool withText;
const LocalSendLogo({required this.withText});
@override
Widget build(BuildContext context) {
final logo = ColorFiltered(
colorFilter: ColorFilter.mode(
Theme.of(context).colorScheme.primary,
BlendMode.srcATop,
),
child: Assets.img.logo512.image(
width: 200,
height: 200,
),
);
if (withText) {
return Column(
children: [
logo,
const Text(
'LocalSend',
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
],
);
} else {
return logo;
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/custom_dropdown_button.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/theme.dart';
/// A [DropdownButton] with a custom theme.
/// Currently, there is no easy way to apply color and border radius to all [DropdownButton].
class CustomDropdownButton<T> extends StatelessWidget {
final T value;
final List<DropdownMenuItem<T>> items;
final ValueChanged<T>? onChanged;
final bool expanded;
const CustomDropdownButton({
required this.value,
required this.items,
this.onChanged,
this.expanded = true,
});
@override
Widget build(BuildContext context) {
return Material(
color: Theme.of(context).inputDecorationTheme.fillColor,
shape: RoundedRectangleBorder(borderRadius: Theme.of(context).inputDecorationTheme.borderRadius),
child: DropdownButton<T>(
value: value,
isExpanded: expanded,
underline: Container(),
borderRadius: Theme.of(context).inputDecorationTheme.borderRadius,
items: items,
onChanged: onChanged == null
? null
: (value) {
if (value != null) {
onChanged!(value);
}
},
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/rotating_widget.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/util/sleep.dart';
class RotatingWidget extends StatefulWidget {
final Duration duration;
final bool spinning;
final bool reverse;
final Widget child;
const RotatingWidget({
required this.duration,
this.spinning = true,
this.reverse = false,
required this.child,
super.key,
});
@override
State<RotatingWidget> createState() => RotatingWidgetState();
}
class RotatingWidgetState extends State<RotatingWidget> {
static const _fps = 30;
static const _tickDuration = 1000 ~/ _fps; // in milliseconds
static const _maxRadians = 6.28; // 360 degrees in radians
double _angle = 0; // in radians
double _anglePerTick = 0;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateAnglePerTick();
_loop();
});
}
void _updateAnglePerTick() {
_anglePerTick = _maxRadians / (widget.duration.inMilliseconds / _tickDuration);
if (widget.reverse) {
_anglePerTick = -_anglePerTick;
}
}
/// This loop has a much greater performance than using [AnimationController].
void _loop() async {
while (true) {
await sleepAsync(_tickDuration);
if (!mounted) {
return;
}
if (!widget.spinning) {
continue;
}
setState(() {
_angle = (_angle + _anglePerTick) % _maxRadians;
});
}
}
@override
Widget build(BuildContext context) {
return Transform.rotate(
angle: _angle,
child: widget.child,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/widget/custom_icon_button.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/util/native/platform_check.dart';
class CustomIconButton extends StatelessWidget {
final VoidCallback? onPressed;
final Widget child;
const CustomIconButton({
required this.onPressed,
required this.child,
super.key,
});
@override
Widget build(BuildContext context) {
return TextButton(
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.onSurface,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
minimumSize: Size.zero,
shape: const CircleBorder(),
padding: checkPlatformIsDesktop() ? const EdgeInsets.symmetric(horizontal: 8, vertical: 16) : const EdgeInsets.all(8),
),
onPressed: onPressed,
child: child,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/sliver/sliver_pinned_header.dart | import 'package:flutter/material.dart';
class SliverPinnedHeader extends StatelessWidget {
final double height;
final Widget child;
const SliverPinnedHeader({required this.height, required this.child});
@override
Widget build(BuildContext context) {
return SliverPersistentHeader(
pinned: true,
delegate: _SliverPersistentHeaderDelegate(
height: height,
child: child,
),
);
}
}
class _SliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
final double height;
final Widget child;
_SliverPersistentHeaderDelegate({
required this.height,
required this.child,
});
@override
double get minExtent => height;
@override
double get maxExtent => height;
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return SizedBox.expand(child: child);
}
@override
bool shouldRebuild(_SliverPersistentHeaderDelegate oldDelegate) {
return true;
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/list_tile/device_placeholder_list_tile.dart | import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/provider/animation_provider.dart';
import 'package:localsend_app/util/device_type_ext.dart';
import 'package:localsend_app/widget/device_bage.dart';
import 'package:localsend_app/widget/list_tile/custom_list_tile.dart';
import 'package:localsend_app/widget/opacity_slideshow.dart';
import 'package:refena_flutter/refena_flutter.dart';
class DevicePlaceholderListTile extends StatelessWidget {
const DevicePlaceholderListTile();
@override
Widget build(BuildContext context) {
final animations = context.ref.watch(animationProvider);
return CustomListTile(
icon: OpacitySlideshow(
durationMillis: 3000,
running: animations,
children: [
...DeviceType.values.map((d) => Icon(d.icon, size: 46)),
],
),
title: const Visibility(
visible: false,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
// A workaround to have an implicit height
child: Text('A', style: TextStyle(fontSize: 20)),
),
subTitle: Wrap(
runSpacing: 10,
spacing: 10,
children: [
DeviceBadge(
backgroundColor: Theme.of(context).colorScheme.onSecondaryContainer.withOpacity(0.5),
foregroundColor: Colors.transparent,
label: ' ',
),
DeviceBadge(
backgroundColor: Theme.of(context).colorScheme.onSecondaryContainer.withOpacity(0.5),
foregroundColor: Colors.transparent,
label: ' ',
),
],
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/list_tile/device_list_tile.dart | import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/util/device_type_ext.dart';
import 'package:localsend_app/util/ip_helper.dart';
import 'package:localsend_app/widget/custom_progress_bar.dart';
import 'package:localsend_app/widget/device_bage.dart';
import 'package:localsend_app/widget/list_tile/custom_list_tile.dart';
class DeviceListTile extends StatelessWidget {
final Device device;
final bool isFavorite;
/// If not null, this name is used instead of [Device.alias].
/// This is the case when the device is marked as favorite.
final String? nameOverride;
final String? info;
final double? progress;
final VoidCallback? onTap;
final VoidCallback? onFavoriteTap;
const DeviceListTile({
required this.device,
this.isFavorite = false,
this.nameOverride,
this.info,
this.progress,
this.onTap,
this.onFavoriteTap,
});
@override
Widget build(BuildContext context) {
final badgeColor = Color.lerp(Theme.of(context).colorScheme.secondaryContainer, Colors.white, 0.3)!;
return CustomListTile(
icon: Icon(device.deviceType.icon, size: 46),
title: Text(nameOverride ?? device.alias, style: const TextStyle(fontSize: 20)),
trailing: onFavoriteTap != null
? IconButton(
icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),
onPressed: onFavoriteTap,
)
: null,
subTitle: Wrap(
runSpacing: 10,
spacing: 10,
children: [
if (info != null)
Text(info!, style: const TextStyle(color: Colors.grey))
else if (progress != null)
Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: CustomProgressBar(progress: progress!),
)
else ...[
DeviceBadge(
backgroundColor: badgeColor,
foregroundColor: Theme.of(context).colorScheme.onSecondaryContainer,
label: '#${device.ip.visualId}',
),
if (device.deviceModel != null)
DeviceBadge(
backgroundColor: badgeColor,
foregroundColor: Theme.of(context).colorScheme.onSecondaryContainer,
label: device.deviceModel!,
),
],
],
),
onTap: onTap,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/list_tile/custom_list_tile.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/theme.dart';
class CustomListTile extends StatelessWidget {
final Widget? icon;
final Widget title;
final Widget subTitle;
final Widget? trailing;
final EdgeInsets padding;
final VoidCallback? onTap;
const CustomListTile({
this.icon,
required this.title,
required this.subTitle,
this.trailing,
this.padding = const EdgeInsets.all(15),
this.onTap,
});
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Theme.of(context).colorScheme.secondaryContainerIfDark,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(10),
child: Padding(
padding: padding,
child: Row(
children: [
if (icon != null) ...[
icon!,
const SizedBox(width: 15),
],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
FittedBox(
child: title,
),
const SizedBox(height: 5),
subTitle,
],
),
),
if (trailing != null) trailing!,
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/message_input_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:routerino/routerino.dart';
class MessageInputDialog extends StatefulWidget {
final String? initialText;
const MessageInputDialog({this.initialText});
@override
State<MessageInputDialog> createState() => _MessageInputDialogState();
}
class _MessageInputDialogState extends State<MessageInputDialog> {
final _textController = TextEditingController();
@override
void initState() {
super.initState();
_textController.text = widget.initialText ?? '';
}
@override
void dispose() {
_textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.messageInput.title),
content: TextFormField(
controller: _textController,
keyboardType: TextInputType.multiline,
maxLines: null,
autofocus: true,
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Theme.of(context).colorScheme.onPrimary,
),
onPressed: () => context.pop(_textController.text),
child: Text(t.general.confirm),
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/not_available_on_platform_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/util/platform_strings.dart';
import 'package:routerino/routerino.dart';
class NotAvailableOnPlatformDialog extends StatelessWidget {
final List<TargetPlatform> platforms;
const NotAvailableOnPlatformDialog({required this.platforms});
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.notAvailableOnPlatform.title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(t.dialogs.notAvailableOnPlatform.content),
const SizedBox(height: 10),
...platforms.map((p) {
return Text('- ${p.humanName}');
}),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/file_name_input_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/util/file_path_helper.dart';
import 'package:routerino/routerino.dart';
class FileNameInputDialog extends StatefulWidget {
final String originalName;
final String initialName;
const FileNameInputDialog({
required this.originalName,
required this.initialName,
});
@override
State<FileNameInputDialog> createState() => _FileNameInputDialogState();
}
class _FileNameInputDialogState extends State<FileNameInputDialog> {
final _textController = TextEditingController();
@override
void initState() {
super.initState();
_textController.text = widget.initialName;
}
void _submit() {
if (mounted) {
String input = _textController.text.trim();
if (!input.contains('.') && widget.originalName.contains('.')) {
// user forgot extension, we fix it
input = input.withExtension(widget.originalName.extension);
}
context.pop(input);
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.fileNameInput.title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(t.dialogs.fileNameInput.original(original: widget.originalName)),
const SizedBox(height: 10),
TextFormField(
controller: _textController,
autofocus: true,
onFieldSubmitted: (_) => _submit,
),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Theme.of(context).colorScheme.onPrimary,
),
onPressed: _submit,
child: Text(t.general.confirm),
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/add_file_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/util/native/file_picker.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/big_button.dart';
import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
class AddFileDialog extends StatelessWidget {
final List<FilePickerOption> options;
const AddFileDialog({required this.options});
static Future<void> open({required BuildContext context, required List<FilePickerOption> options}) async {
if (checkPlatformIsDesktop()) {
await showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(t.dialogs.addFile.title),
content: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 300),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(t.dialogs.addFile.content),
const SizedBox(height: 20),
AddFileDialog(options: options),
],
),
),
actions: [
TextButton(
onPressed: () {
context.pop();
},
child: Text(t.general.close),
)
],
),
);
} else {
await context.pushBottomSheet(() => CustomBottomSheet(
title: t.dialogs.addFile.title,
description: t.dialogs.addFile.content,
child: AddFileDialog(options: options),
));
}
}
@override
Widget build(BuildContext context) {
return Wrap(
spacing: 15,
runSpacing: 15,
children: [
...options.map((option) {
return BigButton(
icon: option.icon,
label: option.label,
filled: true,
onTap: () async {
context.popUntilRoot();
await context.ref.dispatchAsync(PickFileAction(option: option, context: context));
},
);
}),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/custom_bottom_sheet.dart | import 'package:flutter/material.dart';
import 'package:routerino/routerino.dart';
class CustomBottomSheet extends StatelessWidget {
final String title;
final String? description;
final Widget child;
const CustomBottomSheet({
required this.title,
required this.description,
required this.child,
});
@override
Widget build(BuildContext context) {
return RouterinoBottomSheet(
title: title,
description: description,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
borderRadius: 20,
child: child,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/loading_dialog.dart | import 'package:flutter/material.dart';
class LoadingDialog extends StatelessWidget {
const LoadingDialog();
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: const Center(
child: CircularProgressIndicator(),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/address_input_dialog.dart | import 'package:collection/collection.dart';
import 'package:common/common.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/provider/last_devices.provider.dart';
import 'package:localsend_app/provider/local_ip_provider.dart';
import 'package:localsend_app/provider/network/targeted_discovery_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/util/task_runner.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
enum _InputMode {
hashtag,
ip;
String get label {
return switch (this) {
_InputMode.hashtag => t.dialogs.addressInput.hashtag,
_InputMode.ip => t.dialogs.addressInput.ip,
};
}
}
/// A dialog to input an hash or address.
/// Pops the dialog with the device if found.
class AddressInputDialog extends StatefulWidget {
const AddressInputDialog();
@override
State<AddressInputDialog> createState() => _AddressInputDialogState();
}
class _AddressInputDialogState extends State<AddressInputDialog> with Refena {
final _selected = List.generate(_InputMode.values.length, (index) => index == 0);
_InputMode _mode = _InputMode.hashtag;
String _input = '';
bool _fetching = false;
bool _failed = false;
Future<void> _submit(List<String> localIps, int port, [String? candidate]) async {
final List<String> candidates;
final String input = _input.trim();
if (candidate != null) {
candidates = [candidate];
} else if (_mode == _InputMode.ip) {
candidates = [input];
} else {
candidates = localIps.map((ip) => '${ip.ipPrefix}.$input').toList();
}
setState(() {
_fetching = true;
});
final https = ref.read(settingsProvider).https;
final results = TaskRunner<Device?>(
concurrency: 10,
initialTasks: [
for (final ip in candidates) () => ref.read(targetedDiscoveryProvider).discover(ip: ip, port: port, https: https),
],
).stream;
bool found = false;
await for (final device in results) {
if (device != null) {
found = true;
if (mounted) {
ref.redux(lastDevicesProvider).dispatch(AddLastDeviceAction(device));
context.pop(device);
}
break;
}
}
if (!found && mounted) {
setState(() {
_fetching = false;
_failed = true;
});
}
}
@override
Widget build(BuildContext context) {
final localIps = (ref.watch(localIpProvider.select((info) => info.localIps))).uniqueIpPrefix;
final settings = ref.watch(settingsProvider);
final lastDevices = ref.watch(lastDevicesProvider);
return AlertDialog(
title: Text(t.dialogs.addressInput.title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ToggleButtons(
isSelected: _selected,
onPressed: (int index) {
setState(() {
for (int i = 0; i < _selected.length; i++) {
_selected[i] = i == index;
}
_mode = _InputMode.values[index];
});
},
borderRadius: BorderRadius.circular(10),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
constraints: const BoxConstraints(minWidth: 0, minHeight: 0),
children: _InputMode.values.map((mode) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Text(mode.label),
);
}).toList(),
),
const SizedBox(height: 15),
TextFormField(
key: ValueKey('input-$_mode'),
autofocus: true,
enabled: !_fetching,
keyboardType: _mode == _InputMode.hashtag ? TextInputType.number : TextInputType.text,
decoration: InputDecoration(
prefixText: _mode == _InputMode.hashtag ? '# ' : 'IP: ',
),
onChanged: (s) {
setState(() => _input = s);
},
onFieldSubmitted: (s) async => _submit(localIps, settings.port),
),
const SizedBox(height: 10),
if (_mode == _InputMode.hashtag) ...[
Text(
'${t.general.example}: 123',
style: const TextStyle(color: Colors.grey),
),
if (localIps.length <= 1)
Text(
'${t.dialogs.addressInput.ip}: ${localIps.firstOrNull?.ipPrefix ?? '192.168.2'}.$_input',
style: const TextStyle(color: Colors.grey),
)
else ...[
Text(
'${t.dialogs.addressInput.ip}:',
style: const TextStyle(color: Colors.grey),
),
for (final ip in localIps)
Text(
'- ${ip.ipPrefix}.$_input',
style: const TextStyle(color: Colors.grey),
),
],
] else ...[
if (lastDevices.isEmpty)
Text(
'${t.general.example}: ${localIps.firstOrNull?.ipPrefix ?? '192.168.2'}.123',
style: const TextStyle(color: Colors.grey),
)
else
Text.rich(
TextSpan(
children: [
TextSpan(text: t.dialogs.addressInput.recentlyUsed),
...lastDevices.mapIndexed((index, device) {
return [
if (index != 0) const TextSpan(text: ', '),
TextSpan(
text: device.ip,
style: TextStyle(color: Theme.of(context).colorScheme.primary),
recognizer: TapGestureRecognizer()..onTap = () async => _submit(localIps, settings.port, device.ip),
)
];
}).expand((e) => e),
],
),
),
],
if (_failed)
Padding(
padding: const EdgeInsets.only(top: 10),
child: Text(t.general.error, style: TextStyle(color: Theme.of(context).colorScheme.warning)),
),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
FilledButton(
onPressed: _fetching ? null : () async => _submit(localIps, settings.port),
child: Text(t.general.confirm),
),
],
);
}
}
extension on String {
String get ipPrefix {
return split('.').take(3).join('.');
}
}
extension on List<String> {
List<String> get uniqueIpPrefix {
final seen = <String>{};
return where((s) => seen.add(s.ipPrefix)).toList();
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/file_info_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/persistence/receive_history_entry.dart';
import 'package:localsend_app/util/file_size_helper.dart';
import 'package:routerino/routerino.dart';
class FileInfoDialog extends StatelessWidget {
final ReceiveHistoryEntry entry;
const FileInfoDialog({required this.entry, super.key});
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.fileInfo.title),
content: Table(
columnWidths: const {
0: IntrinsicColumnWidth(),
1: IntrinsicColumnWidth(),
2: IntrinsicColumnWidth(),
},
children: [
TableRow(
children: [
Text(t.dialogs.fileInfo.fileName, maxLines: 1),
const SizedBox(width: 10),
SelectableText(entry.fileName),
],
),
TableRow(
children: [
Text(t.dialogs.fileInfo.path),
const SizedBox(width: 10),
SelectableText(entry.savedToGallery ? t.progressPage.savedToGallery : (entry.path ?? '')),
],
),
TableRow(
children: [
Text(t.dialogs.fileInfo.size),
const SizedBox(width: 10),
SelectableText(entry.fileSize.asReadableFileSize),
],
),
TableRow(
children: [
Text(t.dialogs.fileInfo.sender),
const SizedBox(width: 10),
SelectableText(entry.senderAlias),
],
),
TableRow(
children: [
Text(t.dialogs.fileInfo.time),
const SizedBox(width: 10),
SelectableText(entry.timestampString),
],
),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
),
],
);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.