Flutter formatting changes (#252)

* `flutter fmt lib/`

* Re-enable formatting in CI
This commit is contained in:
Caleb Jasik 2025-02-13 15:37:44 -06:00 committed by GitHub
parent b2ebe0289a
commit ed348ab126
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
57 changed files with 2397 additions and 2125 deletions

View file

@ -23,6 +23,5 @@ jobs:
with: with:
show-progress: false show-progress: false
# Disabled for a single PR, this will be re-enabled in the PR that has lots of formatting changes. - name: Check formating
# - name: Check formating run: dart format -l120 lib/ --set-exit-if-changed --suppress-analytics --output none
# run: dart format -l120 lib/ --set-exit-if-changed --suppress-analytics --output none

View file

@ -53,7 +53,8 @@ class _CIDRFieldState extends State<CIDRField> {
var textStyle = CupertinoTheme.of(context).textTheme.textStyle; var textStyle = CupertinoTheme.of(context).textTheme.textStyle;
return Container( return Container(
child: Row(children: <Widget>[ child: Row(
children: <Widget>[
Expanded( Expanded(
child: Padding( child: Padding(
padding: EdgeInsets.fromLTRB(6, 6, 2, 6), padding: EdgeInsets.fromLTRB(6, 6, 2, 6),
@ -74,7 +75,9 @@ class _CIDRFieldState extends State<CIDRField> {
widget.onChanged!(cidr); widget.onChanged!(cidr);
}, },
controller: widget.ipController, controller: widget.ipController,
))), ),
),
),
Text("/"), Text("/"),
Container( Container(
width: Utils.textSize("bits", textStyle).width + 12, width: Utils.textSize("bits", textStyle).width + 12,
@ -96,8 +99,11 @@ class _CIDRFieldState extends State<CIDRField> {
inputFormatters: [FilteringTextInputFormatter.digitsOnly], inputFormatters: [FilteringTextInputFormatter.digitsOnly],
textInputAction: widget.textInputAction ?? TextInputAction.done, textInputAction: widget.textInputAction ?? TextInputAction.done,
placeholder: 'bits', placeholder: 'bits',
)) ),
])); ),
],
),
);
} }
@override @override

View file

@ -46,7 +46,9 @@ class CIDRFormField extends FormField<CIDR> {
field.didChange(value); field.didChange(value);
} }
return Column(crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
CIDRField( CIDRField(
autoFocus: autoFocus, autoFocus: autoFocus,
focusNode: focusNode, focusNode: focusNode,
@ -57,12 +59,16 @@ class CIDRFormField extends FormField<CIDR> {
bitsController: state._effectiveBitsController, bitsController: state._effectiveBitsController,
), ),
field.hasError field.hasError
? Text(field.errorText ?? "Unknown error", ? Text(
field.errorText ?? "Unknown error",
style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13), style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13),
textAlign: TextAlign.end) textAlign: TextAlign.end,
: Container(height: 0) )
]); : Container(height: 0),
}); ],
);
},
);
final TextEditingController? ipController; final TextEditingController? ipController;
final TextEditingController? bitsController; final TextEditingController? bitsController;

View file

@ -17,14 +17,20 @@ class DangerButton extends StatelessWidget {
child: child, child: child,
style: FilledButton.styleFrom( style: FilledButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.error, backgroundColor: Theme.of(context).colorScheme.error,
foregroundColor: Theme.of(context).colorScheme.onError)); foregroundColor: Theme.of(context).colorScheme.onError,
),
);
} else { } else {
// Workaround for https://github.com/flutter/flutter/issues/161590 // Workaround for https://github.com/flutter/flutter/issues/161590
final themeData = CupertinoTheme.of(context); final themeData = CupertinoTheme.of(context);
return CupertinoTheme( return CupertinoTheme(
data: themeData.copyWith(primaryColor: CupertinoColors.white), data: themeData.copyWith(primaryColor: CupertinoColors.white),
child: CupertinoButton( child: CupertinoButton(
child: child, onPressed: onPressed, color: CupertinoColors.systemRed.resolveFrom(context))); child: child,
onPressed: onPressed,
color: CupertinoColors.systemRed.resolveFrom(context),
),
);
} }
} }
} }

View file

@ -5,15 +5,15 @@ import 'package:mobile_nebula/services/utils.dart';
/// SimplePage with a form and built in validation and confirmation to discard changes if any are made /// SimplePage with a form and built in validation and confirmation to discard changes if any are made
class FormPage extends StatefulWidget { class FormPage extends StatefulWidget {
const FormPage( const FormPage({
{Key? key, Key? key,
required this.title, required this.title,
required this.child, required this.child,
required this.onSave, required this.onSave,
required this.changed, required this.changed,
this.hideSave = false, this.hideSave = false,
this.scrollController}) this.scrollController,
: super(key: key); }) : super(key: key);
final String title; final String title;
final Function onSave; final Function onSave;
@ -46,9 +46,15 @@ class _FormPageState extends State<FormPage> {
} }
final NavigatorState navigator = Navigator.of(context); final NavigatorState navigator = Navigator.of(context);
Utils.confirmDelete(context, 'Discard changes?', () { Utils.confirmDelete(
context,
'Discard changes?',
() {
navigator.pop(); navigator.pop();
}, deleteLabel: 'Yes', cancelLabel: 'No'); },
deleteLabel: 'Yes',
cancelLabel: 'No',
);
}, },
child: SimplePage( child: SimplePage(
leadingAction: _buildLeader(context), leadingAction: _buildLeader(context),
@ -57,24 +63,37 @@ class _FormPageState extends State<FormPage> {
title: Text(widget.title), title: Text(widget.title),
child: Form( child: Form(
key: _formKey, key: _formKey,
onChanged: () => setState(() { onChanged:
() => setState(() {
changed = true; changed = true;
}), }),
child: widget.child), child: widget.child,
)); ),
),
);
} }
Widget _buildLeader(BuildContext context) { Widget _buildLeader(BuildContext context) {
return Utils.leadingBackWidget(context, label: changed ? 'Cancel' : 'Back', onPressed: () { return Utils.leadingBackWidget(
context,
label: changed ? 'Cancel' : 'Back',
onPressed: () {
if (changed) { if (changed) {
Utils.confirmDelete(context, 'Discard changes?', () { Utils.confirmDelete(
context,
'Discard changes?',
() {
changed = false; changed = false;
Navigator.pop(context); Navigator.pop(context);
}, deleteLabel: 'Yes', cancelLabel: 'No'); },
deleteLabel: 'Yes',
cancelLabel: 'No',
);
} else { } else {
Navigator.pop(context); Navigator.pop(context);
} }
}); },
);
} }
List<Widget> _buildTrailer(BuildContext context) { List<Widget> _buildTrailer(BuildContext context) {
@ -83,9 +102,7 @@ class _FormPageState extends State<FormPage> {
} }
return [ return [
Utils.trailingSaveWidget( Utils.trailingSaveWidget(context, () {
context,
() {
if (_formKey.currentState == null) { if (_formKey.currentState == null) {
return; return;
} }
@ -96,8 +113,7 @@ class _FormPageState extends State<FormPage> {
_formKey.currentState!.save(); _formKey.currentState!.save();
widget.onSave(); widget.onSave();
}, }),
)
]; ];
} }
} }

View file

@ -59,7 +59,8 @@ class _IPAndPortFieldState extends State<IPAndPortField> {
var textStyle = CupertinoTheme.of(context).textTheme.textStyle; var textStyle = CupertinoTheme.of(context).textTheme.textStyle;
return Container( return Container(
child: Row(children: <Widget>[ child: Row(
children: <Widget>[
Expanded( Expanded(
child: Padding( child: Padding(
padding: EdgeInsets.fromLTRB(6, 6, 2, 6), padding: EdgeInsets.fromLTRB(6, 6, 2, 6),
@ -76,7 +77,9 @@ class _IPAndPortFieldState extends State<IPAndPortField> {
}, },
textAlign: widget.ipTextAlign, textAlign: widget.ipTextAlign,
controller: widget.ipController, controller: widget.ipController,
))), ),
),
),
Text(":"), Text(":"),
Container( Container(
width: Utils.textSize("00000", textStyle).width + 12, width: Utils.textSize("00000", textStyle).width + 12,
@ -94,8 +97,11 @@ class _IPAndPortFieldState extends State<IPAndPortField> {
inputFormatters: [FilteringTextInputFormatter.digitsOnly], inputFormatters: [FilteringTextInputFormatter.digitsOnly],
textInputAction: TextInputAction.done, textInputAction: TextInputAction.done,
placeholder: 'port', placeholder: 'port',
)) ),
])); ),
],
),
);
} }
@override @override

View file

@ -52,7 +52,8 @@ class IPAndPortFormField extends FormField<IPAndPort> {
field.didChange(value); field.didChange(value);
} }
return Column(children: <Widget>[ return Column(
children: <Widget>[
IPAndPortField( IPAndPortField(
ipOnly: ipOnly, ipOnly: ipOnly,
ipHelp: ipHelp, ipHelp: ipHelp,
@ -67,11 +68,15 @@ class IPAndPortFormField extends FormField<IPAndPort> {
ipTextAlign: ipTextAlign, ipTextAlign: ipTextAlign,
), ),
field.hasError field.hasError
? Text(field.errorText!, ? Text(
style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13)) field.errorText!,
: Container(height: 0) style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13),
]); )
}); : Container(height: 0),
],
);
},
);
final TextEditingController? ipController; final TextEditingController? ipController;
final TextEditingController? portController; final TextEditingController? portController;
@ -109,8 +114,10 @@ class _IPAndPortFormField extends FormFieldState<IPAndPort> {
@override @override
void didUpdateWidget(IPAndPortFormField oldWidget) { void didUpdateWidget(IPAndPortFormField oldWidget) {
super.didUpdateWidget(oldWidget); super.didUpdateWidget(oldWidget);
var update = var update = IPAndPort(
IPAndPort(ip: widget.ipController?.text, port: int.tryParse(widget.portController?.text ?? "") ?? null); ip: widget.ipController?.text,
port: int.tryParse(widget.portController?.text ?? "") ?? null,
);
bool shouldUpdate = false; bool shouldUpdate = false;
if (widget.ipController != oldWidget.ipController) { if (widget.ipController != oldWidget.ipController) {

View file

@ -16,8 +16,8 @@ class IPField extends StatelessWidget {
final controller; final controller;
final textAlign; final textAlign;
const IPField( const IPField({
{Key? key, Key? key,
this.ipOnly = false, this.ipOnly = false,
this.help = "ip address", this.help = "ip address",
this.autoFocus = false, this.autoFocus = false,
@ -27,8 +27,8 @@ class IPField extends StatelessWidget {
this.textPadding = const EdgeInsets.all(6.0), this.textPadding = const EdgeInsets.all(6.0),
this.textInputAction, this.textInputAction,
this.controller, this.controller,
this.textAlign = TextAlign.center}) this.textAlign = TextAlign.center,
: super(key: key); }) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -50,7 +50,8 @@ class IPField extends StatelessWidget {
inputFormatters: ipOnly ? [IPTextInputFormatter()] : [FilteringTextInputFormatter.allow(RegExp(r'[^\s]+'))], inputFormatters: ipOnly ? [IPTextInputFormatter()] : [FilteringTextInputFormatter.allow(RegExp(r'[^\s]+'))],
textInputAction: this.textInputAction, textInputAction: this.textInputAction,
placeholder: help, placeholder: help,
)); ),
);
} }
} }
@ -59,16 +60,13 @@ class IPTextInputFormatter extends TextInputFormatter {
@override @override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
return _selectionAwareTextManipulation( return _selectionAwareTextManipulation(newValue, (String substring) {
newValue,
(String substring) {
return whitelistedPattern return whitelistedPattern
.allMatches(substring) .allMatches(substring)
.map<String>((Match match) => match.group(0)!) .map<String>((Match match) => match.group(0)!)
.join() .join()
.replaceAll(RegExp(r','), '.'); .replaceAll(RegExp(r','), '.');
}, });
);
} }
} }

View file

@ -50,7 +50,9 @@ class IPFormField extends FormField<String> {
field.didChange(value); field.didChange(value);
} }
return Column(crossAxisAlignment: crossAxisAlignment, children: <Widget>[ return Column(
crossAxisAlignment: crossAxisAlignment,
children: <Widget>[
IPField( IPField(
ipOnly: ipOnly, ipOnly: ipOnly,
help: help, help: help,
@ -61,16 +63,19 @@ class IPFormField extends FormField<String> {
textPadding: textPadding, textPadding: textPadding,
textInputAction: textInputAction, textInputAction: textInputAction,
controller: state._effectiveController, controller: state._effectiveController,
textAlign: textAlign), textAlign: textAlign,
),
field.hasError field.hasError
? Text( ? Text(
field.errorText!, field.errorText!,
style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13), style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13),
textAlign: textAlign, textAlign: textAlign,
) )
: Container(height: 0) : Container(height: 0),
]); ],
}); );
},
);
final TextEditingController? controller; final TextEditingController? controller;

View file

@ -5,8 +5,8 @@ import 'package:mobile_nebula/components/SpecialTextField.dart';
class PlatformTextFormField extends FormField<String> { class PlatformTextFormField extends FormField<String> {
//TODO: auto-validate, enabled? //TODO: auto-validate, enabled?
PlatformTextFormField( PlatformTextFormField({
{Key? key, Key? key,
widgetKey, widgetKey,
this.controller, this.controller,
focusNode, focusNode,
@ -28,8 +28,8 @@ class PlatformTextFormField extends FormField<String> {
String? initialValue, String? initialValue,
String? placeholder, String? placeholder,
FormFieldValidator<String>? validator, FormFieldValidator<String>? validator,
ValueChanged<String?>? onSaved}) ValueChanged<String?>? onSaved,
: super( }) : super(
key: key, key: key,
initialValue: controller != null ? controller.text : (initialValue ?? ''), initialValue: controller != null ? controller.text : (initialValue ?? ''),
onSaved: onSaved, onSaved: onSaved,
@ -50,7 +50,9 @@ class PlatformTextFormField extends FormField<String> {
field.didChange(value); field.didChange(value);
} }
return Column(crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
SpecialTextField( SpecialTextField(
key: widgetKey, key: widgetKey,
controller: state._effectiveController, controller: state._effectiveController,
@ -70,16 +72,19 @@ class PlatformTextFormField extends FormField<String> {
textAlignVertical: textAlignVertical, textAlignVertical: textAlignVertical,
placeholder: placeholder, placeholder: placeholder,
inputFormatters: inputFormatters, inputFormatters: inputFormatters,
suffix: suffix), suffix: suffix,
),
field.hasError field.hasError
? Text( ? Text(
field.errorText!, field.errorText!,
style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13), style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13),
textAlign: textAlign, textAlign: textAlign,
) )
: Container(height: 0) : Container(height: 0),
]); ],
}); );
},
);
final TextEditingController? controller; final TextEditingController? controller;

View file

@ -2,16 +2,11 @@ import 'package:flutter/material.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart';
enum SimpleScrollable { enum SimpleScrollable { none, vertical, horizontal, both }
none,
vertical,
horizontal,
both,
}
class SimplePage extends StatelessWidget { class SimplePage extends StatelessWidget {
const SimplePage( const SimplePage({
{Key? key, Key? key,
required this.title, required this.title,
required this.child, required this.child,
this.leadingAction, this.leadingAction,
@ -23,8 +18,8 @@ class SimplePage extends StatelessWidget {
this.onRefresh, this.onRefresh,
this.onLoading, this.onLoading,
this.alignment, this.alignment,
this.refreshController}) this.refreshController,
: super(key: key); }) : super(key: key);
final Widget title; final Widget title;
final Widget child; final Widget child;
@ -54,7 +49,8 @@ class SimplePage extends StatelessWidget {
realChild = SingleChildScrollView( realChild = SingleChildScrollView(
scrollDirection: Axis.vertical, scrollDirection: Axis.vertical,
child: realChild, child: realChild,
controller: refreshController == null ? scrollController : null); controller: refreshController == null ? scrollController : null,
);
addScrollbar = true; addScrollbar = true;
} }
@ -77,7 +73,8 @@ class SimplePage extends StatelessWidget {
enablePullUp: onLoading != null, enablePullUp: onLoading != null,
enablePullDown: onRefresh != null, enablePullDown: onRefresh != null,
footer: ClassicFooter(loadStyle: LoadStyle.ShowWhenLoading), footer: ClassicFooter(loadStyle: LoadStyle.ShowWhenLoading),
)); ),
);
addScrollbar = true; addScrollbar = true;
} }
@ -90,10 +87,7 @@ class SimplePage extends StatelessWidget {
} }
if (bottomBar != null) { if (bottomBar != null) {
realChild = Column(children: [ realChild = Column(children: [Expanded(child: realChild), bottomBar!]);
Expanded(child: realChild),
bottomBar!,
]);
} }
return PlatformScaffold( return PlatformScaffold(
@ -102,12 +96,15 @@ class SimplePage extends StatelessWidget {
title: title, title: title,
leading: leadingAction, leading: leadingAction,
trailingActions: trailingActions, trailingActions: trailingActions,
cupertino: (_, __) => CupertinoNavigationBarData( cupertino:
(_, __) => CupertinoNavigationBarData(
transitionBetweenRoutes: false, transitionBetweenRoutes: false,
// TODO: set title on route, show here instead of just "Back" // TODO: set title on route, show here instead of just "Back"
previousPageTitle: 'Back', previousPageTitle: 'Back',
padding: EdgeInsetsDirectional.only(end: 8.0)), padding: EdgeInsetsDirectional.only(end: 8.0),
), ),
body: SafeArea(child: realChild)); ),
body: SafeArea(child: realChild),
);
} }
} }

View file

@ -13,7 +13,8 @@ class SiteItem extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final borderColor = site.errors.length > 0 final borderColor =
site.errors.length > 0
? CupertinoColors.systemRed.resolveFrom(context) ? CupertinoColors.systemRed.resolveFrom(context)
: site.connected : site.connected
? CupertinoColors.systemGreen.resolveFrom(context) ? CupertinoColors.systemGreen.resolveFrom(context)
@ -23,7 +24,8 @@ class SiteItem extends StatelessWidget {
return Container( return Container(
margin: EdgeInsets.symmetric(vertical: 6), margin: EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(border: Border(left: border)), decoration: BoxDecoration(border: Border(left: border)),
child: _buildContent(context)); child: _buildContent(context),
);
} }
Widget _buildContent(BuildContext context) { Widget _buildContent(BuildContext context) {
@ -32,8 +34,10 @@ class SiteItem extends StatelessWidget {
Theme.of(context).brightness == Brightness.dark ? 'images/dn-logo-dark.svg' : 'images/dn-logo-light.svg'; Theme.of(context).brightness == Brightness.dark ? 'images/dn-logo-dark.svg' : 'images/dn-logo-light.svg';
return SpecialButton( return SpecialButton(
decoration: decoration: BoxDecoration(
BoxDecoration(border: Border(top: border, bottom: border), color: Utils.configItemBackground(context)), border: Border(top: border, bottom: border),
color: Utils.configItemBackground(context),
),
onPressed: onPressed, onPressed: onPressed,
child: Padding( child: Padding(
padding: EdgeInsets.fromLTRB(10, 10, 5, 10), padding: EdgeInsets.fromLTRB(10, 10, 5, 10),
@ -45,8 +49,10 @@ class SiteItem extends StatelessWidget {
: Container(), : Container(),
Expanded(child: Text(site.name, style: TextStyle(fontWeight: FontWeight.bold))), Expanded(child: Text(site.name, style: TextStyle(fontWeight: FontWeight.bold))),
Padding(padding: EdgeInsets.only(right: 10)), Padding(padding: EdgeInsets.only(right: 10)),
Icon(CupertinoIcons.forward, color: CupertinoColors.placeholderText.resolveFrom(context), size: 18) Icon(CupertinoIcons.forward, color: CupertinoColors.placeholderText.resolveFrom(context), size: 18),
], ],
))); ),
),
);
} }
} }

View file

@ -16,15 +16,15 @@ class SiteTitle extends StatelessWidget {
return IntrinsicWidth( return IntrinsicWidth(
child: Padding( child: Padding(
padding: EdgeInsets.symmetric(horizontal: 16), padding: EdgeInsets.symmetric(horizontal: 16),
child: Row(children: [ child: Row(
children: [
site.managed site.managed
? Padding(padding: EdgeInsets.only(right: 10), child: SvgPicture.asset(dnIcon, width: 12)) ? Padding(padding: EdgeInsets.only(right: 10), child: SvgPicture.asset(dnIcon, width: 12))
: Container(), : Container(),
Expanded( Expanded(child: Text(site.name, overflow: TextOverflow.ellipsis)),
child: Text( ],
site.name, ),
overflow: TextOverflow.ellipsis, ),
)) );
])));
} }
} }

View file

@ -36,10 +36,9 @@ class _SpecialButtonState extends State<SpecialButton> with SingleTickerProvider
child: Ink( child: Ink(
decoration: widget.decoration, decoration: widget.decoration,
color: widget.color, color: widget.color,
child: InkWell( child: InkWell(child: widget.child, onTap: widget.onPressed),
child: widget.child, ),
onTap: widget.onPressed, );
)));
} }
Widget _buildGeneric() { Widget _buildGeneric() {
@ -63,7 +62,8 @@ class _SpecialButtonState extends State<SpecialButton> with SingleTickerProvider
child: DefaultTextStyle(style: textStyle, child: Container(child: widget.child, color: widget.color)), child: DefaultTextStyle(style: textStyle, child: Container(child: widget.child, color: widget.color)),
), ),
), ),
)); ),
);
} }
// Eyeballed values. Feel free to tweak. // Eyeballed values. Feel free to tweak.
@ -77,11 +77,7 @@ class _SpecialButtonState extends State<SpecialButton> with SingleTickerProvider
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_animationController = AnimationController( _animationController = AnimationController(duration: const Duration(milliseconds: 200), value: 0.0, vsync: this);
duration: const Duration(milliseconds: 200),
value: 0.0,
vsync: this,
);
_opacityAnimation = _animationController!.drive(CurveTween(curve: Curves.decelerate)).drive(_opacityTween); _opacityAnimation = _animationController!.drive(CurveTween(curve: Curves.decelerate)).drive(_opacityTween);
_setTween(); _setTween();
} }
@ -131,7 +127,8 @@ class _SpecialButtonState extends State<SpecialButton> with SingleTickerProvider
} }
final bool wasHeldDown = _buttonHeldDown; final bool wasHeldDown = _buttonHeldDown;
final TickerFuture ticker = _buttonHeldDown final TickerFuture ticker =
_buttonHeldDown
? _animationController!.animateTo(1.0, duration: kFadeOutDuration) ? _animationController!.animateTo(1.0, duration: kFadeOutDuration)
: _animationController!.animateTo(0.0, duration: kFadeInDuration); : _animationController!.animateTo(0.0, duration: kFadeInDuration);

View file

@ -4,8 +4,8 @@ import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
/// A normal TextField or CupertinoTextField that looks the same on all platforms /// A normal TextField or CupertinoTextField that looks the same on all platforms
class SpecialTextField extends StatefulWidget { class SpecialTextField extends StatefulWidget {
const SpecialTextField( const SpecialTextField({
{Key? key, Key? key,
this.placeholder, this.placeholder,
this.suffix, this.suffix,
this.controller, this.controller,
@ -27,8 +27,8 @@ class SpecialTextField extends StatefulWidget {
this.expands, this.expands,
this.keyboardAppearance, this.keyboardAppearance,
this.textAlignVertical, this.textAlignVertical,
this.inputFormatters}) this.inputFormatters,
: super(key: key); }) : super(key: key);
final String? placeholder; final String? placeholder;
final TextEditingController? controller; final TextEditingController? controller;
@ -98,20 +98,26 @@ class _SpecialTextFieldState extends State<SpecialTextField> {
}, },
expands: widget.expands, expands: widget.expands,
inputFormatters: formatters, inputFormatters: formatters,
material: (_, __) => MaterialTextFieldData( material:
(_, __) => MaterialTextFieldData(
decoration: InputDecoration( decoration: InputDecoration(
border: InputBorder.none, border: InputBorder.none,
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
isDense: true, isDense: true,
hintText: widget.placeholder, hintText: widget.placeholder,
counterText: '', counterText: '',
suffix: widget.suffix)), suffix: widget.suffix,
cupertino: (_, __) => CupertinoTextFieldData( ),
),
cupertino:
(_, __) => CupertinoTextFieldData(
decoration: BoxDecoration(), decoration: BoxDecoration(),
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
placeholder: widget.placeholder, placeholder: widget.placeholder,
suffix: widget.suffix), suffix: widget.suffix,
),
style: widget.style, style: widget.style,
controller: widget.controller); controller: widget.controller,
);
} }
} }

View file

@ -15,14 +15,19 @@ class PrimaryButton extends StatelessWidget {
return FilledButton( return FilledButton(
onPressed: onPressed, onPressed: onPressed,
child: child, child: child,
style: FilledButton.styleFrom(backgroundColor: Theme.of(context).colorScheme.primary)); style: FilledButton.styleFrom(backgroundColor: Theme.of(context).colorScheme.primary),
);
} else { } else {
// Workaround for https://github.com/flutter/flutter/issues/161590 // Workaround for https://github.com/flutter/flutter/issues/161590
final themeData = CupertinoTheme.of(context); final themeData = CupertinoTheme.of(context);
return CupertinoTheme( return CupertinoTheme(
data: themeData.copyWith(primaryColor: CupertinoColors.white), data: themeData.copyWith(primaryColor: CupertinoColors.white),
child: CupertinoButton( child: CupertinoButton(
child: child, onPressed: onPressed, color: CupertinoColors.secondaryLabel.resolveFrom(context))); child: child,
onPressed: onPressed,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
),
);
} }
} }
} }

View file

@ -19,6 +19,7 @@ class ConfigButtonItem extends StatelessWidget {
child: Container( child: Container(
constraints: BoxConstraints(minHeight: Utils.minInteractiveSize, minWidth: double.infinity), constraints: BoxConstraints(minHeight: Utils.minInteractiveSize, minWidth: double.infinity),
child: Center(child: content), child: Center(child: content),
)); ),
);
} }
} }

View file

@ -3,9 +3,14 @@ import 'package:mobile_nebula/components/SpecialButton.dart';
import 'package:mobile_nebula/services/utils.dart'; import 'package:mobile_nebula/services/utils.dart';
class ConfigCheckboxItem extends StatelessWidget { class ConfigCheckboxItem extends StatelessWidget {
const ConfigCheckboxItem( const ConfigCheckboxItem({
{Key? key, this.label, this.content, this.labelWidth = 100, this.onChanged, this.checked = false}) Key? key,
: super(key: key); this.label,
this.content,
this.labelWidth = 100,
this.onChanged,
this.checked = false,
}) : super(key: key);
final Widget? label; final Widget? label;
final Widget? content; final Widget? content;
@ -25,9 +30,10 @@ class ConfigCheckboxItem extends StatelessWidget {
Expanded(child: Container(child: content, padding: EdgeInsets.only(right: 10))), Expanded(child: Container(child: content, padding: EdgeInsets.only(right: 10))),
checked checked
? Icon(CupertinoIcons.check_mark, color: CupertinoColors.systemBlue.resolveFrom(context)) ? Icon(CupertinoIcons.check_mark, color: CupertinoColors.systemBlue.resolveFrom(context))
: Container() : Container(),
], ],
)); ),
);
if (onChanged != null) { if (onChanged != null) {
return SpecialButton( return SpecialButton(

View file

@ -20,10 +20,9 @@ class ConfigHeader extends StatelessWidget {
padding: const EdgeInsets.only(left: 10.0, top: 30.0, bottom: 5.0, right: 10.0), padding: const EdgeInsets.only(left: 10.0, top: 30.0, bottom: 5.0, right: 10.0),
child: Text( child: Text(
label, label,
style: basicTextStyle(context).copyWith( style: basicTextStyle(
color: color ?? CupertinoColors.secondaryLabel.resolveFrom(context), context,
fontSize: _headerFontSize, ).copyWith(color: color ?? CupertinoColors.secondaryLabel.resolveFrom(context), fontSize: _headerFontSize),
),
), ),
); );
} }

View file

@ -5,13 +5,13 @@ import 'package:flutter/material.dart';
import 'package:mobile_nebula/services/utils.dart'; import 'package:mobile_nebula/services/utils.dart';
class ConfigItem extends StatelessWidget { class ConfigItem extends StatelessWidget {
const ConfigItem( const ConfigItem({
{Key? key, Key? key,
this.label, this.label,
required this.content, required this.content,
this.labelWidth = 100, this.labelWidth = 100,
this.crossAxisAlignment = CrossAxisAlignment.center}) this.crossAxisAlignment = CrossAxisAlignment.center,
: super(key: key); }) : super(key: key);
final Widget? label; final Widget? label;
final Widget content; final Widget content;
@ -37,6 +37,7 @@ class ConfigItem extends StatelessWidget {
Container(width: labelWidth, child: DefaultTextStyle(style: textStyle, child: Container(child: label))), Container(width: labelWidth, child: DefaultTextStyle(style: textStyle, child: Container(child: label))),
Expanded(child: DefaultTextStyle(style: textStyle, child: Container(child: content))), Expanded(child: DefaultTextStyle(style: textStyle, child: Container(child: content))),
], ],
)); ),
);
} }
} }

View file

@ -6,15 +6,15 @@ import 'package:mobile_nebula/components/SpecialButton.dart';
import 'package:mobile_nebula/services/utils.dart'; import 'package:mobile_nebula/services/utils.dart';
class ConfigPageItem extends StatelessWidget { class ConfigPageItem extends StatelessWidget {
const ConfigPageItem( const ConfigPageItem({
{Key? key, Key? key,
this.label, this.label,
this.content, this.content,
this.labelWidth = 100, this.labelWidth = 100,
this.onPressed, this.onPressed,
this.disabled = false, this.disabled = false,
this.crossAxisAlignment = CrossAxisAlignment.center}) this.crossAxisAlignment = CrossAxisAlignment.center,
: super(key: key); }) : super(key: key);
final Widget? label; final Widget? label;
final Widget? content; final Widget? content;
@ -30,8 +30,10 @@ class ConfigPageItem extends StatelessWidget {
if (Platform.isAndroid) { if (Platform.isAndroid) {
final origTheme = Theme.of(context); final origTheme = Theme.of(context);
theme = origTheme.copyWith( theme = origTheme.copyWith(
textTheme: origTheme.textTheme textTheme: origTheme.textTheme.copyWith(
.copyWith(labelLarge: origTheme.textTheme.labelLarge!.copyWith(fontWeight: FontWeight.normal))); labelLarge: origTheme.textTheme.labelLarge!.copyWith(fontWeight: FontWeight.normal),
),
);
return Theme(data: theme, child: _buildContent(context)); return Theme(data: theme, child: _buildContent(context));
} else { } else {
final origTheme = CupertinoTheme.of(context); final origTheme = CupertinoTheme.of(context);
@ -54,9 +56,10 @@ class ConfigPageItem extends StatelessWidget {
Expanded(child: Container(child: content, padding: EdgeInsets.only(right: 10))), Expanded(child: Container(child: content, padding: EdgeInsets.only(right: 10))),
this.disabled this.disabled
? Container() ? Container()
: Icon(CupertinoIcons.forward, color: CupertinoColors.placeholderText.resolveFrom(context), size: 18) : Icon(CupertinoIcons.forward, color: CupertinoColors.placeholderText.resolveFrom(context), size: 18),
], ],
)), ),
),
); );
} }
} }

View file

@ -27,19 +27,27 @@ class ConfigSection extends StatelessWidget {
if (children[i + 1].runtimeType.toString() == 'ConfigButtonItem') { if (children[i + 1].runtimeType.toString() == 'ConfigButtonItem') {
pad = 0; pad = 0;
} }
_children.add(Padding( _children.add(
child: Divider(height: 1, color: Utils.configSectionBorder(context)), padding: EdgeInsets.only(left: pad))); Padding(
child: Divider(height: 1, color: Utils.configSectionBorder(context)),
padding: EdgeInsets.only(left: pad),
),
);
} }
} }
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
label != null ? ConfigHeader(label: label!, color: labelColor) : Container(height: 20), label != null ? ConfigHeader(label: label!, color: labelColor) : Container(height: 20),
Container( Container(
decoration: decoration: BoxDecoration(
BoxDecoration(border: Border(top: border, bottom: border), color: Utils.configItemBackground(context)), border: Border(top: border, bottom: border),
child: Column( color: Utils.configItemBackground(context),
children: _children, ),
)) child: Column(children: _children),
]); ),
],
);
} }
} }

View file

@ -1,9 +1,12 @@
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
class ConfigTextItem extends StatelessWidget { class ConfigTextItem extends StatelessWidget {
const ConfigTextItem( const ConfigTextItem({
{Key? key, this.placeholder, this.controller, this.style = const TextStyle(fontFamily: 'RobotoMono')}) Key? key,
: super(key: key); this.placeholder,
this.controller,
this.style = const TextStyle(fontFamily: 'RobotoMono'),
}) : super(key: key);
final String? placeholder; final String? placeholder;
final TextEditingController? controller; final TextEditingController? controller;

View file

@ -19,16 +19,13 @@ Future<void> main() async {
var settings = Settings(); var settings = Settings();
if (settings.trackErrors) { if (settings.trackErrors) {
await SentryFlutter.init( await SentryFlutter.init((options) {
(options) {
options.dsn = 'https://96106df405ade3f013187dfc8e4200e7@o920269.ingest.us.sentry.io/4508132321001472'; options.dsn = 'https://96106df405ade3f013187dfc8e4200e7@o920269.ingest.us.sentry.io/4508132321001472';
// Capture all traces. May need to adjust if overwhelming // Capture all traces. May need to adjust if overwhelming
options.tracesSampleRate = 1.0; options.tracesSampleRate = 1.0;
// For each trace, capture all profiles // For each trace, capture all profiles
options.profilesSampleRate = 1.0; options.profilesSampleRate = 1.0;
}, }, appRunner: () => runApp(Main()));
appRunner: () => runApp(Main()),
);
} else { } else {
runApp(Main()); runApp(Main());
} }
@ -91,7 +88,8 @@ class _AppState extends State<App> {
return PlatformProvider( return PlatformProvider(
settings: PlatformSettingsData(iosUsesMaterialWidgets: true), settings: PlatformSettingsData(iosUsesMaterialWidgets: true),
builder: (context) => PlatformApp( builder:
(context) => PlatformApp(
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
localizationsDelegates: <LocalizationsDelegate<dynamic>>[ localizationsDelegates: <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate, DefaultMaterialLocalizations.delegate,
@ -105,9 +103,7 @@ class _AppState extends State<App> {
theme: brightness == Brightness.light ? theme.light() : theme.dark(), theme: brightness == Brightness.light ? theme.light() : theme.dark(),
); );
}, },
cupertino: (_, __) => CupertinoAppData( cupertino: (_, __) => CupertinoAppData(theme: CupertinoThemeData(brightness: brightness)),
theme: CupertinoThemeData(brightness: brightness),
),
onGenerateRoute: (settings) { onGenerateRoute: (settings) {
if (settings.name == '/') { if (settings.name == '/') {
return platformPageRoute(context: context, builder: (context) => MainScreen(this.dnEnrolled)); return platformPageRoute(context: context, builder: (context) => MainScreen(this.dnEnrolled));
@ -118,7 +114,8 @@ class _AppState extends State<App> {
// TODO: maybe implement this as a dialog instead of a page, you can stack multiple enrollment screens which is annoying in dev // TODO: maybe implement this as a dialog instead of a page, you can stack multiple enrollment screens which is annoying in dev
return platformPageRoute( return platformPageRoute(
context: context, context: context,
builder: (context) => builder:
(context) =>
EnrollmentScreen(code: EnrollmentScreen.parseCode(settings.name!), stream: this.dnEnrolled), EnrollmentScreen(code: EnrollmentScreen.parseCode(settings.name!), stream: this.dnEnrolled),
); );
} }

View file

@ -19,9 +19,6 @@ class CIDR {
throw 'Invalid CIDR string'; throw 'Invalid CIDR string';
} }
return CIDR( return CIDR(ip: parts[0], bits: int.parse(parts[1]));
ip: parts[0],
bits: int.parse(parts[1]),
);
} }
} }

View file

@ -24,10 +24,7 @@ class Certificate {
String fingerprint; String fingerprint;
String signature; String signature;
Certificate.debug() Certificate.debug() : this.details = CertificateDetails.debug(), this.fingerprint = "DEBUG", this.signature = "DEBUG";
: this.details = CertificateDetails.debug(),
this.fingerprint = "DEBUG",
this.signature = "DEBUG";
Certificate.fromJson(Map<String, dynamic> json) Certificate.fromJson(Map<String, dynamic> json)
: details = CertificateDetails.fromJson(json['details']), : details = CertificateDetails.fromJson(json['details']),
@ -73,11 +70,7 @@ class CertificateValidity {
bool valid; bool valid;
String reason; String reason;
CertificateValidity.debug() CertificateValidity.debug() : this.valid = true, this.reason = "";
: this.valid = true,
this.reason = "";
CertificateValidity.fromJson(Map<String, dynamic> json) CertificateValidity.fromJson(Map<String, dynamic> json) : valid = json['Valid'], reason = json['Reason'];
: valid = json['Valid'],
reason = json['Reason'];
} }

View file

@ -52,10 +52,7 @@ class UDPAddress {
String ip; String ip;
int port; int port;
UDPAddress({ UDPAddress({required this.ip, required this.port});
required this.ip,
required this.port,
});
@override @override
String toString() { String toString() {

View file

@ -21,9 +21,6 @@ class IPAndPort {
//TODO: Uri.parse is as close as I could get to parsing both ipv4 and v6 addresses with a port without bringing a whole mess of code into here //TODO: Uri.parse is as close as I could get to parsing both ipv4 and v6 addresses with a port without bringing a whole mess of code into here
final uri = Uri.parse("ugh://$val"); final uri = Uri.parse("ugh://$val");
return IPAndPort( return IPAndPort(ip: uri.host, port: uri.port);
ip: uri.host,
port: uri.port,
);
} }
} }

View file

@ -94,7 +94,8 @@ class Site {
this.lastManagedUpdate = lastManagedUpdate; this.lastManagedUpdate = lastManagedUpdate;
_updates = EventChannel('net.defined.nebula/${this.id}'); _updates = EventChannel('net.defined.nebula/${this.id}');
_updates.receiveBroadcastStream().listen((d) { _updates.receiveBroadcastStream().listen(
(d) {
try { try {
_updateFromJson(d); _updateFromJson(d);
_change.add(null); _change.add(null);
@ -102,11 +103,13 @@ class Site {
//TODO: handle the error //TODO: handle the error
print(err); print(err);
} }
}, onError: (err) { },
onError: (err) {
_updateFromJson(err.details); _updateFromJson(err.details);
var error = err as PlatformException; var error = err as PlatformException;
_change.addError(error.message ?? 'An unexpected error occurred'); _change.addError(error.message ?? 'An unexpected error occurred');
}); },
);
} }
factory Site.fromJson(Map<String, dynamic> json) { factory Site.fromJson(Map<String, dynamic> json) {
@ -220,9 +223,11 @@ class Site {
'id': id, 'id': id,
'staticHostmap': staticHostmap, 'staticHostmap': staticHostmap,
'unsafeRoutes': unsafeRoutes, 'unsafeRoutes': unsafeRoutes,
'ca': ca.map((cert) { 'ca': ca
.map((cert) {
return cert.rawCert; return cert.rawCert;
}).join('\n'), })
.join('\n'),
'cert': certInfo?.rawCert, 'cert': certInfo?.rawCert,
'key': key, 'key': key,
'lhDuration': lhDuration, 'lhDuration': lhDuration,
@ -341,8 +346,11 @@ class Site {
Future<HostInfo?> getHostInfo(String vpnIp, bool pending) async { Future<HostInfo?> getHostInfo(String vpnIp, bool pending) async {
try { try {
var ret = await platform var ret = await platform.invokeMethod("active.getHostInfo", <String, dynamic>{
.invokeMethod("active.getHostInfo", <String, dynamic>{"id": id, "vpnIp": vpnIp, "pending": pending}); "id": id,
"vpnIp": vpnIp,
"pending": pending,
});
final h = jsonDecode(ret); final h = jsonDecode(ret);
if (h == null) { if (h == null) {
return null; return null;
@ -358,8 +366,11 @@ class Site {
Future<HostInfo?> setRemoteForTunnel(String vpnIp, String addr) async { Future<HostInfo?> setRemoteForTunnel(String vpnIp, String addr) async {
try { try {
var ret = await platform var ret = await platform.invokeMethod("active.setRemoteForTunnel", <String, dynamic>{
.invokeMethod("active.setRemoteForTunnel", <String, dynamic>{"id": id, "vpnIp": vpnIp, "addr": addr}); "id": id,
"vpnIp": vpnIp,
"addr": addr,
});
final h = jsonDecode(ret); final h = jsonDecode(ret);
if (h == null) { if (h == null) {
return null; return null;

View file

@ -14,16 +14,10 @@ class StaticHost {
result.add(IPAndPort.fromString(item)); result.add(IPAndPort.fromString(item));
}); });
return StaticHost( return StaticHost(lighthouse: json['lighthouse'], destinations: result);
lighthouse: json['lighthouse'],
destinations: result,
);
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {'lighthouse': lighthouse, 'destinations': destinations};
'lighthouse': lighthouse,
'destinations': destinations,
};
} }
} }

View file

@ -5,16 +5,10 @@ class UnsafeRoute {
UnsafeRoute({this.route, this.via}); UnsafeRoute({this.route, this.via});
factory UnsafeRoute.fromJson(Map<String, dynamic> json) { factory UnsafeRoute.fromJson(Map<String, dynamic> json) {
return UnsafeRoute( return UnsafeRoute(route: json['route'], via: json['via']);
route: json['route'],
via: json['via'],
);
} }
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
return { return {'route': route, 'via': via};
'route': route,
'via': via,
};
} }
} }

View file

@ -37,52 +37,67 @@ class _AboutScreenState extends State<AboutScreen> {
// packageInfo is null until ready is true // packageInfo is null until ready is true
if (!ready) { if (!ready) {
return Center( return Center(
child: PlatformCircularProgressIndicator(cupertino: (_, __) { child: PlatformCircularProgressIndicator(
cupertino: (_, __) {
return CupertinoProgressIndicatorData(radius: 50); return CupertinoProgressIndicatorData(radius: 50);
}), },
),
); );
} }
return SimplePage( return SimplePage(
title: Text('About'), title: Text('About'),
child: Column(children: [ child: Column(
ConfigSection(children: <Widget>[ children: [
ConfigSection(
children: <Widget>[
ConfigItem( ConfigItem(
label: Text('App version'), label: Text('App version'),
labelWidth: 150, labelWidth: 150,
content: _buildText('${packageInfo!.version}-${packageInfo!.buildNumber} (sha: $gitSha)')), content: _buildText('${packageInfo!.version}-${packageInfo!.buildNumber} (sha: $gitSha)'),
),
ConfigItem( ConfigItem(
label: Text('Nebula version'), labelWidth: 150, content: _buildText('$nebulaVersion ($goVersion)')), label: Text('Nebula version'),
labelWidth: 150,
content: _buildText('$nebulaVersion ($goVersion)'),
),
ConfigItem( ConfigItem(
label: Text('Flutter version'), label: Text('Flutter version'),
labelWidth: 150, labelWidth: 150,
content: _buildText(flutterVersion['frameworkVersion'] ?? 'Unknown')), content: _buildText(flutterVersion['frameworkVersion'] ?? 'Unknown'),
),
ConfigItem( ConfigItem(
label: Text('Dart version'), label: Text('Dart version'),
labelWidth: 150, labelWidth: 150,
content: _buildText(flutterVersion['dartSdkVersion'] ?? 'Unknown')), content: _buildText(flutterVersion['dartSdkVersion'] ?? 'Unknown'),
]), ),
ConfigSection(children: <Widget>[ ],
),
ConfigSection(
children: <Widget>[
//TODO: wire up these other pages //TODO: wire up these other pages
// ConfigPageItem(label: Text('Changelog'), labelWidth: 300, onPressed: () => Utils.launchUrl('https://defined.net/mobile/changelog', context)), // ConfigPageItem(label: Text('Changelog'), labelWidth: 300, onPressed: () => Utils.launchUrl('https://defined.net/mobile/changelog', context)),
ConfigPageItem( ConfigPageItem(
label: Text('Privacy policy'), label: Text('Privacy policy'),
labelWidth: 300, labelWidth: 300,
onPressed: () => Utils.launchUrl('https://www.defined.net/privacy/', context)), onPressed: () => Utils.launchUrl('https://www.defined.net/privacy/', context),
),
ConfigPageItem( ConfigPageItem(
label: Text('Licenses'), label: Text('Licenses'),
labelWidth: 300, labelWidth: 300,
onPressed: () => Utils.openPage(context, (context) { onPressed:
() => Utils.openPage(context, (context) {
return LicensesScreen(); return LicensesScreen();
})), }),
]), ),
],
),
Padding( Padding(
padding: EdgeInsets.only(top: 20), padding: EdgeInsets.only(top: 20),
child: Text( child: Text('Copyright © 2024 Defined Networking, Inc', textAlign: TextAlign.center),
'Copyright © 2024 Defined Networking, Inc', ),
textAlign: TextAlign.center, ],
)), ),
]),
); );
} }

View file

@ -98,8 +98,10 @@ class _EnrollmentScreenState extends State<EnrollmentScreen> {
child: Text( child: Text(
'No valid enrollment code was found.\n\nContact your administrator to obtain a new enrollment code.', 'No valid enrollment code was found.\n\nContact your administrator to obtain a new enrollment code.',
textAlign: TextAlign.center, textAlign: TextAlign.center,
)), ),
padding: EdgeInsets.only(top: 20)); ),
padding: EdgeInsets.only(top: 20),
);
} }
} else if (this.error != null) { } else if (this.error != null) {
// Error while enrolling, display it // Error while enrolling, display it
@ -108,15 +110,20 @@ class _EnrollmentScreenState extends State<EnrollmentScreen> {
children: [ children: [
Padding( Padding(
child: SelectableText( child: SelectableText(
'There was an issue while attempting to enroll this device. Contact your administrator to obtain a new enrollment code.'), 'There was an issue while attempting to enroll this device. Contact your administrator to obtain a new enrollment code.',
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20)), ),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
),
Padding( Padding(
child: SelectableText.rich(TextSpan(children: [ child: SelectableText.rich(
TextSpan(
children: [
TextSpan(text: 'If the problem persists, please let us know at '), TextSpan(text: 'If the problem persists, please let us know at '),
TextSpan( TextSpan(
text: 'support@defined.net', text: 'support@defined.net',
style: bodyTextStyle.apply(color: colorScheme.primary), style: bodyTextStyle.apply(color: colorScheme.primary),
recognizer: TapGestureRecognizer() recognizer:
TapGestureRecognizer()
..onTap = () async { ..onTap = () async {
if (await canLaunchUrl(contactUri)) { if (await canLaunchUrl(contactUri)) {
print(await launchUrl(contactUri)); print(await launchUrl(contactUri));
@ -124,8 +131,11 @@ class _EnrollmentScreenState extends State<EnrollmentScreen> {
}, },
), ),
TextSpan(text: ' and provide the following error:'), TextSpan(text: ' and provide the following error:'),
])), ],
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10)), ),
),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
),
Container( Container(
child: Padding(child: SelectableText(this.error!), padding: EdgeInsets.all(16)), child: Padding(child: SelectableText(this.error!), padding: EdgeInsets.all(16)),
color: Theme.of(context).colorScheme.errorContainer, color: Theme.of(context).colorScheme.errorContainer,
@ -133,26 +143,29 @@ class _EnrollmentScreenState extends State<EnrollmentScreen> {
], ],
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
)); ),
);
} else if (this.enrolled) { } else if (this.enrolled) {
// Enrollment complete! // Enrollment complete!
child = Padding( child = Padding(
child: Center( child: Center(child: Text('Enrollment complete! 🎉', textAlign: TextAlign.center)),
child: Text( padding: EdgeInsets.only(top: 20),
'Enrollment complete! 🎉', );
textAlign: TextAlign.center,
)),
padding: EdgeInsets.only(top: 20));
} else { } else {
// Have a code and actively enrolling // Have a code and actively enrolling
alignment = Alignment.center; alignment = Alignment.center;
child = Center( child = Center(
child: Column(children: [ child: Column(
children: [
Padding(child: Text('Contacting DN for enrollment'), padding: EdgeInsets.only(bottom: 25)), Padding(child: Text('Contacting DN for enrollment'), padding: EdgeInsets.only(bottom: 25)),
PlatformCircularProgressIndicator(cupertino: (_, __) { PlatformCircularProgressIndicator(
cupertino: (_, __) {
return CupertinoProgressIndicatorData(radius: 50); return CupertinoProgressIndicatorData(radius: 50);
}) },
])); ),
],
),
);
} }
return SimplePage(title: Text('Enroll with Managed Nebula'), child: child, alignment: alignment); return SimplePage(title: Text('Enroll with Managed Nebula'), child: child, alignment: alignment);
@ -187,27 +200,21 @@ class _EnrollmentScreenState extends State<EnrollmentScreen> {
controller: enrollInput, controller: enrollInput,
validator: validator, validator: validator,
hintText: 'from admin.defined.net', hintText: 'from admin.defined.net',
cupertino: (_, __) => CupertinoTextFormFieldData( cupertino: (_, __) => CupertinoTextFormFieldData(prefix: Text("Code or link")),
prefix: Text("Code or link"), material: (_, __) => MaterialTextFormFieldData(decoration: const InputDecoration(labelText: 'Code or link')),
), ),
material: (_, __) => MaterialTextFormFieldData(
decoration: const InputDecoration(labelText: 'Code or link'),
),
));
final form = Form(
key: _formKey,
child: Platform.isAndroid ? input : ConfigSection(children: [input]),
); );
return Column(children: [ final form = Form(key: _formKey, child: Platform.isAndroid ? input : ConfigSection(children: [input]));
Padding(
padding: EdgeInsets.symmetric(vertical: 32), return Column(
child: form, children: [
), Padding(padding: EdgeInsets.symmetric(vertical: 32), child: form),
Padding( Padding(
padding: EdgeInsets.symmetric(horizontal: 16), padding: EdgeInsets.symmetric(horizontal: 16),
child: Row(children: [Expanded(child: PrimaryButton(child: Text('Submit'), onPressed: onSubmit))])) child: Row(children: [Expanded(child: PrimaryButton(child: Text('Submit'), onPressed: onSubmit))]),
]); ),
],
);
} }
} }

View file

@ -60,42 +60,59 @@ class _HostInfoScreenState extends State<HostInfoScreen> {
refreshController.refreshCompleted(); refreshController.refreshCompleted();
}, },
child: Column( child: Column(
children: [_buildMain(), _buildDetails(), _buildRemotes(), !widget.pending ? _buildClose() : Container()])); children: [_buildMain(), _buildDetails(), _buildRemotes(), !widget.pending ? _buildClose() : Container()],
),
);
} }
Widget _buildMain() { Widget _buildMain() {
return ConfigSection(children: [ return ConfigSection(
children: [
ConfigItem(label: Text('VPN IP'), labelWidth: 150, content: SelectableText(hostInfo.vpnIp)), ConfigItem(label: Text('VPN IP'), labelWidth: 150, content: SelectableText(hostInfo.vpnIp)),
hostInfo.cert != null hostInfo.cert != null
? ConfigPageItem( ? ConfigPageItem(
label: Text('Certificate'), label: Text('Certificate'),
labelWidth: 150, labelWidth: 150,
content: Text(hostInfo.cert!.details.name), content: Text(hostInfo.cert!.details.name),
onPressed: () => Utils.openPage( onPressed:
() => Utils.openPage(
context, context,
(context) => CertificateDetailsScreen( (context) => CertificateDetailsScreen(
certInfo: CertificateInfo(cert: hostInfo.cert!), certInfo: CertificateInfo(cert: hostInfo.cert!),
supportsQRScanning: widget.supportsQRScanning, supportsQRScanning: widget.supportsQRScanning,
))) ),
),
)
: Container(), : Container(),
]); ],
);
} }
Widget _buildDetails() { Widget _buildDetails() {
return ConfigSection(children: <Widget>[ return ConfigSection(
children: <Widget>[
ConfigItem( ConfigItem(
label: Text('Lighthouse'), labelWidth: 150, content: SelectableText(widget.isLighthouse ? 'Yes' : 'No')), label: Text('Lighthouse'),
labelWidth: 150,
content: SelectableText(widget.isLighthouse ? 'Yes' : 'No'),
),
ConfigItem(label: Text('Local Index'), labelWidth: 150, content: SelectableText('${hostInfo.localIndex}')), ConfigItem(label: Text('Local Index'), labelWidth: 150, content: SelectableText('${hostInfo.localIndex}')),
ConfigItem(label: Text('Remote Index'), labelWidth: 150, content: SelectableText('${hostInfo.remoteIndex}')), ConfigItem(label: Text('Remote Index'), labelWidth: 150, content: SelectableText('${hostInfo.remoteIndex}')),
ConfigItem( ConfigItem(
label: Text('Message Counter'), labelWidth: 150, content: SelectableText('${hostInfo.messageCounter}')), label: Text('Message Counter'),
]); labelWidth: 150,
content: SelectableText('${hostInfo.messageCounter}'),
),
],
);
} }
Widget _buildRemotes() { Widget _buildRemotes() {
if (hostInfo.remoteAddresses.length == 0) { if (hostInfo.remoteAddresses.length == 0) {
return ConfigSection( return ConfigSection(
label: 'REMOTES', children: [ConfigItem(content: Text('No remote addresses yet'), labelWidth: 0)]); label: 'REMOTES',
children: [ConfigItem(content: Text('No remote addresses yet'), labelWidth: 0)],
);
} }
return widget.pending ? _buildStaticRemotes() : _buildEditRemotes(); return widget.pending ? _buildStaticRemotes() : _buildEditRemotes();
@ -109,7 +126,8 @@ class _HostInfoScreenState extends State<HostInfoScreen> {
hostInfo.remoteAddresses.forEach((remoteObj) { hostInfo.remoteAddresses.forEach((remoteObj) {
String remote = remoteObj.toString(); String remote = remoteObj.toString();
items.add(ConfigCheckboxItem( items.add(
ConfigCheckboxItem(
key: Key(remote), key: Key(remote),
label: Text(remote), //TODO: need to do something to adjust the font size in the event we have an ipv6 address label: Text(remote), //TODO: need to do something to adjust the font size in the event we have an ipv6 address
labelWidth: ipWidth, labelWidth: ipWidth,
@ -128,7 +146,8 @@ class _HostInfoScreenState extends State<HostInfoScreen> {
Utils.popError(context, 'Error while changing the remote', err.toString()); Utils.popError(context, 'Error while changing the remote', err.toString());
} }
}, },
)); ),
);
}); });
return ConfigSection(label: items.length > 0 ? 'Tap to change the active address' : null, children: items); return ConfigSection(label: items.length > 0 ? 'Tap to change the active address' : null, children: items);
@ -142,12 +161,14 @@ class _HostInfoScreenState extends State<HostInfoScreen> {
hostInfo.remoteAddresses.forEach((remoteObj) { hostInfo.remoteAddresses.forEach((remoteObj) {
String remote = remoteObj.toString(); String remote = remoteObj.toString();
items.add(ConfigCheckboxItem( items.add(
ConfigCheckboxItem(
key: Key(remote), key: Key(remote),
label: Text(remote), //TODO: need to do something to adjust the font size in the event we have an ipv6 address label: Text(remote), //TODO: need to do something to adjust the font size in the event we have an ipv6 address
labelWidth: ipWidth, labelWidth: ipWidth,
checked: currentRemote == remote, checked: currentRemote == remote,
)); ),
);
}); });
return ConfigSection(label: items.length > 0 ? 'REMOTES' : null, children: items); return ConfigSection(label: items.length > 0 ? 'REMOTES' : null, children: items);
@ -160,7 +181,8 @@ class _HostInfoScreenState extends State<HostInfoScreen> {
width: double.infinity, width: double.infinity,
child: DangerButton( child: DangerButton(
child: Text('Close Tunnel'), child: Text('Close Tunnel'),
onPressed: () => Utils.confirmDelete(context, 'Close Tunnel?', () async { onPressed:
() => Utils.confirmDelete(context, 'Close Tunnel?', () async {
try { try {
await widget.site.closeTunnel(hostInfo.vpnIp); await widget.site.closeTunnel(hostInfo.vpnIp);
if (widget.onChanged != null) { if (widget.onChanged != null) {
@ -170,7 +192,10 @@ class _HostInfoScreenState extends State<HostInfoScreen> {
} catch (err) { } catch (err) {
Utils.popError(context, 'Error while trying to close the tunnel', err.toString()); Utils.popError(context, 'Error while trying to close the tunnel', err.toString());
} }
}, deleteLabel: 'Close')))); }, deleteLabel: 'Close'),
),
),
);
} }
_getHostInfo() async { _getHostInfo() async {

View file

@ -25,19 +25,12 @@ class LicensesScreen extends StatelessWidget {
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
child: PlatformListTile( child: PlatformListTile(
onTap: () { onTap: () {
Utils.openPage( Utils.openPage(context, (_) => LicenceDetailPage(title: capitalize(dep.name), licence: dep.license!));
context,
(_) => LicenceDetailPage(
title: capitalize(dep.name),
licence: dep.license!,
),
);
}, },
title: Text( title: Text(capitalize(dep.name)),
capitalize(dep.name),
),
subtitle: Text(dep.description), subtitle: Text(dep.description),
trailing: Icon(context.platformIcons.forward, size: 18)), trailing: Icon(context.platformIcons.forward, size: 18),
),
); );
}, },
), ),
@ -62,14 +55,7 @@ class LicenceDetailPage extends StatelessWidget {
decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)), decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
child: SingleChildScrollView( child: SingleChildScrollView(
physics: const BouncingScrollPhysics(), physics: const BouncingScrollPhysics(),
child: Column( child: Column(children: [Text(licence, style: const TextStyle(fontSize: 15))]),
children: [
Text(
licence,
style: const TextStyle(fontSize: 15),
),
],
),
), ),
), ),
), ),

View file

@ -115,11 +115,7 @@ class _MainScreenState extends State<MainScreen> {
if (kDebugMode) { if (kDebugMode) {
debugSite = Row( debugSite = Row(
children: [ children: [_debugSave(badDebugSave), _debugSave(goodDebugSave), _debugClearKeys()],
_debugSave(badDebugSave),
_debugSave(goodDebugSave),
_debugClearKeys(),
],
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
); );
} }
@ -141,12 +137,14 @@ class _MainScreenState extends State<MainScreen> {
leadingAction: PlatformIconButton( leadingAction: PlatformIconButton(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
icon: Icon(Icons.add, size: 28.0), icon: Icon(Icons.add, size: 28.0),
onPressed: () => Utils.openPage(context, (context) { onPressed:
() => Utils.openPage(context, (context) {
return SiteConfigScreen( return SiteConfigScreen(
onSave: (_) { onSave: (_) {
_loadSites(); _loadSites();
}, },
supportsQRScanning: supportsQRScanning); supportsQRScanning: supportsQRScanning,
);
}), }),
), ),
refreshController: refreshController, refreshController: refreshController,
@ -175,7 +173,9 @@ class _MainScreenState extends State<MainScreen> {
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: error!, children: error!,
), ),
padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10))); padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
),
);
} }
return _buildSites(); return _buildSites();
@ -191,11 +191,14 @@ class _MainScreenState extends State<MainScreen> {
padding: const EdgeInsets.fromLTRB(0, 8.0, 0, 8.0), padding: const EdgeInsets.fromLTRB(0, 8.0, 0, 8.0),
child: Text('Welcome to Nebula!', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)), child: Text('Welcome to Nebula!', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
), ),
Text('You don\'t have any site configurations installed yet. Hit the plus button above to get started.', Text(
textAlign: TextAlign.center), 'You don\'t have any site configurations installed yet. Hit the plus button above to get started.',
textAlign: TextAlign.center,
),
], ],
), ),
)); ),
);
} }
Widget _buildSites() { Widget _buildSites() {
@ -205,7 +208,8 @@ class _MainScreenState extends State<MainScreen> {
List<Widget> items = []; List<Widget> items = [];
sites!.forEach((site) { sites!.forEach((site) {
items.add(SiteItem( items.add(
SiteItem(
key: Key(site.id), key: Key(site.id),
site: site, site: site,
onPressed: () { onPressed: () {
@ -216,7 +220,9 @@ class _MainScreenState extends State<MainScreen> {
supportsQRScanning: supportsQRScanning, supportsQRScanning: supportsQRScanning,
); );
}); });
})); },
),
);
}); });
Widget child = ReorderableListView( Widget child = ReorderableListView(
@ -250,7 +256,8 @@ class _MainScreenState extends State<MainScreen> {
} }
_loadSites(); _loadSites();
}); },
);
if (Platform.isIOS) { if (Platform.isIOS) {
child = CupertinoTheme(child: child, data: CupertinoTheme.of(context)); child = CupertinoTheme(child: child, data: CupertinoTheme.of(context));
@ -272,11 +279,13 @@ class _MainScreenState extends State<MainScreen> {
staticHostmap: { staticHostmap: {
"10.1.0.1": StaticHost( "10.1.0.1": StaticHost(
lighthouse: true, lighthouse: true,
destinations: [IPAndPort(ip: '10.1.1.53', port: 4242), IPAndPort(ip: '1::1', port: 4242)]) destinations: [IPAndPort(ip: '10.1.1.53', port: 4242), IPAndPort(ip: '1::1', port: 4242)],
),
}, },
ca: [CertificateInfo.debug(rawCert: siteConfig['ca'])], ca: [CertificateInfo.debug(rawCert: siteConfig['ca'])],
certInfo: CertificateInfo.debug(rawCert: siteConfig['cert']), certInfo: CertificateInfo.debug(rawCert: siteConfig['cert']),
unsafeRoutes: [UnsafeRoute(route: '10.3.3.3/32', via: '10.1.0.1')]); unsafeRoutes: [UnsafeRoute(route: '10.3.3.3/32', via: '10.1.0.1')],
);
s.key = siteConfig['key']; s.key = siteConfig['key'];
@ -309,14 +318,17 @@ class _MainScreenState extends State<MainScreen> {
var site = Site.fromJson(rawSite); var site = Site.fromJson(rawSite);
//TODO: we need to cancel change listeners when we rebuild //TODO: we need to cancel change listeners when we rebuild
site.onChange().listen((_) { site.onChange().listen(
(_) {
setState(() {}); setState(() {});
}, onError: (err) { },
onError: (err) {
setState(() {}); setState(() {});
if (ModalRoute.of(context)!.isCurrent) { if (ModalRoute.of(context)!.isCurrent) {
Utils.popError(context, "${site.name} Error", err); Utils.popError(context, "${site.name} Error", err);
} }
}); },
);
sites!.add(site); sites!.add(site);
} catch (err) { } catch (err) {

View file

@ -38,7 +38,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
List<Widget> colorSection = []; List<Widget> colorSection = [];
colorSection.add(ConfigItem( colorSection.add(
ConfigItem(
label: Text('Use system colors'), label: Text('Use system colors'),
labelWidth: 200, labelWidth: 200,
content: Align( content: Align(
@ -49,11 +50,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
settings.useSystemColors = value; settings.useSystemColors = value;
}, },
value: settings.useSystemColors, value: settings.useSystemColors,
)), ),
)); ),
),
);
if (!settings.useSystemColors) { if (!settings.useSystemColors) {
colorSection.add(ConfigItem( colorSection.add(
ConfigItem(
label: Text('Dark mode'), label: Text('Dark mode'),
content: Align( content: Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
@ -63,13 +67,16 @@ class _SettingsScreenState extends State<SettingsScreen> {
settings.darkMode = value; settings.darkMode = value;
}, },
value: settings.darkMode, value: settings.darkMode,
)), ),
)); ),
),
);
} }
List<Widget> items = []; List<Widget> items = [];
items.add(ConfigSection(children: colorSection)); items.add(ConfigSection(children: colorSection));
items.add(ConfigItem( items.add(
ConfigItem(
label: Text('Wrap log output'), label: Text('Wrap log output'),
labelWidth: 200, labelWidth: 200,
content: Align( content: Align(
@ -82,10 +89,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
settings.logWrap = value; settings.logWrap = value;
}); });
}, },
)), ),
)); ),
),
);
items.add(ConfigSection(children: [ items.add(
ConfigSection(
children: [
ConfigItem( ConfigItem(
label: Text('Report errors automatically'), label: Text('Report errors automatically'),
labelWidth: 250, labelWidth: 250,
@ -99,27 +110,35 @@ class _SettingsScreenState extends State<SettingsScreen> {
settings.trackErrors = value; settings.trackErrors = value;
}); });
}, },
))), ),
])); ),
),
],
),
);
items.add(ConfigSection(children: [ items.add(
ConfigSection(
children: [
ConfigPageItem( ConfigPageItem(
label: Text('Enroll with Managed Nebula'), label: Text('Enroll with Managed Nebula'),
labelWidth: 250, labelWidth: 250,
onPressed: () => onPressed:
Utils.openPage(context, (context) => EnrollmentScreen(stream: widget.stream, allowCodeEntry: true))) () =>
])); Utils.openPage(context, (context) => EnrollmentScreen(stream: widget.stream, allowCodeEntry: true)),
),
items.add(ConfigSection(children: [ ],
ConfigPageItem( ),
label: Text('About'),
onPressed: () => Utils.openPage(context, (context) => AboutScreen()),
)
]));
return SimplePage(
title: Text('Settings'),
child: Column(children: items),
); );
items.add(
ConfigSection(
children: [
ConfigPageItem(label: Text('About'), onPressed: () => Utils.openPage(context, (context) => AboutScreen())),
],
),
);
return SimplePage(title: Text('Settings'), child: Column(children: items));
} }
} }

View file

@ -23,12 +23,8 @@ import '../components/SiteTitle.dart';
//TODO: ios is now the problem with connecting screwing our ability to query the hostmap (its a race) //TODO: ios is now the problem with connecting screwing our ability to query the hostmap (its a race)
class SiteDetailScreen extends StatefulWidget { class SiteDetailScreen extends StatefulWidget {
const SiteDetailScreen({ const SiteDetailScreen({Key? key, required this.site, this.onChanged, required this.supportsQRScanning})
Key? key, : super(key: key);
required this.site,
this.onChanged,
required this.supportsQRScanning,
}) : super(key: key);
final Site site; final Site site;
final Function? onChanged; final Function? onChanged;
@ -54,7 +50,8 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
_listHostmap(); _listHostmap();
} }
onChange = site.onChange().listen((_) { onChange = site.onChange().listen(
(_) {
// TODO: Gross hack... we get site.connected = true to trigger the toggle before the VPN service has started. // TODO: Gross hack... we get site.connected = true to trigger the toggle before the VPN service has started.
// If we fetch the hostmap now we'll never get a response. Wait until Nebula is running. // If we fetch the hostmap now we'll never get a response. Wait until Nebula is running.
if (site.status == 'Connected') { if (site.status == 'Connected') {
@ -65,10 +62,12 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
} }
setState(() {}); setState(() {});
}, onError: (err) { },
onError: (err) {
setState(() {}); setState(() {});
Utils.popError(context, "Error", err); Utils.popError(context, "Error", err);
}); },
);
super.initState(); super.initState();
} }
@ -85,12 +84,15 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
return SimplePage( return SimplePage(
title: title, title: title,
leadingAction: Utils.leadingBackWidget(context, onPressed: () { leadingAction: Utils.leadingBackWidget(
context,
onPressed: () {
if (changed && widget.onChanged != null) { if (changed && widget.onChanged != null) {
widget.onChanged!(); widget.onChanged!();
} }
Navigator.pop(context); Navigator.pop(context);
}), },
),
refreshController: refreshController, refreshController: refreshController,
onRefresh: () async { onRefresh: () async {
if (site.connected && site.status == "Connected") { if (site.connected && site.status == "Connected") {
@ -98,13 +100,16 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
} }
refreshController.refreshCompleted(); refreshController.refreshCompleted();
}, },
child: Column(children: [ child: Column(
children: [
_buildErrors(), _buildErrors(),
_buildConfig(), _buildConfig(),
site.connected ? _buildHosts() : Container(), site.connected ? _buildHosts() : Container(),
_buildSiteDetails(), _buildSiteDetails(),
_buildDelete(), _buildDelete(),
])); ],
),
);
} }
Widget _buildErrors() { Widget _buildErrors() {
@ -114,8 +119,12 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
List<Widget> items = []; List<Widget> items = [];
site.errors.forEach((error) { site.errors.forEach((error) {
items.add(ConfigItem( items.add(
labelWidth: 0, content: Padding(padding: EdgeInsets.symmetric(vertical: 10), child: SelectableText(error)))); ConfigItem(
labelWidth: 0,
content: Padding(padding: EdgeInsets.symmetric(vertical: 10), child: SelectableText(error)),
),
);
}); });
return ConfigSection( return ConfigSection(
@ -140,20 +149,28 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
} }
} }
return ConfigSection(children: <Widget>[ return ConfigSection(
children: <Widget>[
ConfigItem( ConfigItem(
label: Text('Status'), label: Text('Status'),
content: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ content: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding( Padding(
padding: EdgeInsets.only(right: 5), padding: EdgeInsets.only(right: 5),
child: Text(widget.site.status, child: Text(
style: TextStyle(color: CupertinoColors.secondaryLabel.resolveFrom(context)))), widget.site.status,
style: TextStyle(color: CupertinoColors.secondaryLabel.resolveFrom(context)),
),
),
Switch.adaptive( Switch.adaptive(
value: widget.site.connected, value: widget.site.connected,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
onChanged: widget.site.errors.length > 0 && !widget.site.connected ? null : handleChange, onChanged: widget.site.errors.length > 0 && !widget.site.connected ? null : handleChange,
) ),
])), ],
),
),
ConfigPageItem( ConfigPageItem(
label: Text('Logs'), label: Text('Logs'),
onPressed: () { onPressed: () {
@ -162,7 +179,8 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
}); });
}, },
), ),
]); ],
);
} }
Widget _buildHosts() { Widget _buildHosts() {
@ -199,10 +217,12 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
}); });
}, },
supportsQRScanning: widget.supportsQRScanning, supportsQRScanning: widget.supportsQRScanning,
)); ),
);
}, },
label: Text("Active"), label: Text("Active"),
content: Container(alignment: Alignment.centerRight, child: active)), content: Container(alignment: Alignment.centerRight, child: active),
),
ConfigPageItem( ConfigPageItem(
onPressed: () { onPressed: () {
if (pendingHosts == null) return; if (pendingHosts == null) return;
@ -219,16 +239,19 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
}); });
}, },
supportsQRScanning: widget.supportsQRScanning, supportsQRScanning: widget.supportsQRScanning,
)); ),
);
}, },
label: Text("Pending"), label: Text("Pending"),
content: Container(alignment: Alignment.centerRight, child: pending)) content: Container(alignment: Alignment.centerRight, child: pending),
),
], ],
); );
} }
Widget _buildSiteDetails() { Widget _buildSiteDetails() {
return ConfigSection(children: <Widget>[ return ConfigSection(
children: <Widget>[
ConfigPageItem( ConfigPageItem(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
content: Text('Configuration'), content: Text('Configuration'),
@ -245,7 +268,8 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
}); });
}, },
), ),
]); ],
);
} }
Widget _buildDelete() { Widget _buildDelete() {
@ -255,12 +279,15 @@ class _SiteDetailScreenState extends State<SiteDetailScreen> {
width: double.infinity, width: double.infinity,
child: DangerButton( child: DangerButton(
child: Text('Delete'), child: Text('Delete'),
onPressed: () => Utils.confirmDelete(context, 'Delete Site?', () async { onPressed:
() => Utils.confirmDelete(context, 'Delete Site?', () async {
if (await _deleteSite()) { if (await _deleteSite()) {
Navigator.of(context).pop(); Navigator.of(context).pop();
} }
}), }),
))); ),
),
);
} }
_listHostmap() async { _listHostmap() async {

View file

@ -64,16 +64,17 @@ class _SiteLogsScreenState extends State<SiteLogsScreen> {
constraints: logBoxConstraints(context), constraints: logBoxConstraints(context),
child: ListenableBuilder( child: ListenableBuilder(
listenable: logsNotifier, listenable: logsNotifier,
builder: (context, child) => SelectableText( builder:
switch (logsNotifier.logsResult) { (context, child) => SelectableText(switch (logsNotifier.logsResult) {
Ok<String>(:var value) => value.trim(), Ok<String>(:var value) => value.trim(),
Error<String>(:var error) => error is LogsNotFoundException Error<String>(:var error) =>
error is LogsNotFoundException
? error.error() ? error.error()
: Utils.popError(context, "Error while reading logs.", error.toString()), : Utils.popError(context, "Error while reading logs.", error.toString()),
null => "", null => "",
}, }, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)),
style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), ),
)), ),
bottomBar: _buildBottomBar(), bottomBar: _buildBottomBar(),
); );
} }
@ -88,10 +89,11 @@ class _SiteLogsScreenState extends State<SiteLogsScreen> {
sizeStyle: CupertinoButtonSize.small, sizeStyle: CupertinoButtonSize.small,
borderRadius: const BorderRadius.all(Radius.circular(8)), borderRadius: const BorderRadius.all(Radius.circular(8)),
child: const Icon(Icons.wrap_text), child: const Icon(Icons.wrap_text),
onPressed: () => { onPressed:
() => {
setState(() { setState(() {
settings.logWrap = !settings.logWrap; settings.logWrap = !settings.logWrap;
}) }),
}, },
), ),
) )
@ -101,20 +103,17 @@ class _SiteLogsScreenState extends State<SiteLogsScreen> {
// The variants of wrap_text seem to be the same, but this seems most correct. // The variants of wrap_text seem to be the same, but this seems most correct.
selectedIcon: const Icon(Icons.wrap_text_outlined), selectedIcon: const Icon(Icons.wrap_text_outlined),
icon: const Icon(Icons.wrap_text), icon: const Icon(Icons.wrap_text),
onPressed: () => { onPressed:
() => {
setState(() { setState(() {
settings.logWrap = !settings.logWrap; settings.logWrap = !settings.logWrap;
}) }),
}, },
); );
} }
Widget _buildBottomBar() { Widget _buildBottomBar() {
var borderSide = BorderSide( var borderSide = BorderSide(color: CupertinoColors.separator, style: BorderStyle.solid, width: 0.0);
color: CupertinoColors.separator,
style: BorderStyle.solid,
width: 0.0,
);
var padding = Platform.isAndroid ? EdgeInsets.fromLTRB(0, 20, 0, 30) : EdgeInsets.all(10); var padding = Platform.isAndroid ? EdgeInsets.fromLTRB(0, 20, 0, 30) : EdgeInsets.all(10);
@ -128,10 +127,12 @@ class _SiteLogsScreenState extends State<SiteLogsScreen> {
child: PlatformIconButton( child: PlatformIconButton(
icon: Icon(context.platformIcons.share), icon: Icon(context.platformIcons.share),
onPressed: () { onPressed: () {
Share.shareFile(context, Share.shareFile(
context,
title: '${widget.site.name} logs', title: '${widget.site.name} logs',
filePath: widget.site.logFile, filePath: widget.site.logFile,
filename: '${widget.site.name}.log'); filename: '${widget.site.name}.log',
);
}, },
), ),
), ),
@ -140,20 +141,21 @@ class _SiteLogsScreenState extends State<SiteLogsScreen> {
child: PlatformIconButton( child: PlatformIconButton(
icon: Icon(context.platformIcons.downArrow), icon: Icon(context.platformIcons.downArrow),
onPressed: () async { onPressed: () async {
controller.animateTo(controller.position.maxScrollExtent, controller.animateTo(
duration: const Duration(milliseconds: 500), curve: Curves.linearToEaseOut); controller.position.maxScrollExtent,
duration: const Duration(milliseconds: 500),
curve: Curves.linearToEaseOut,
);
}, },
), ),
), ),
], ],
), ),
cupertino: (context, child, platform) => Container( cupertino:
decoration: BoxDecoration( (context, child, platform) =>
border: Border(top: borderSide), Container(decoration: BoxDecoration(border: Border(top: borderSide)), padding: padding, child: child),
), material: (context, child, platform) => BottomAppBar(child: child),
padding: padding, );
child: child),
material: (context, child, platform) => BottomAppBar(child: child));
} }
logBoxConstraints(BuildContext context) { logBoxConstraints(BuildContext context) {

View file

@ -53,15 +53,17 @@ class _SiteTunnelsScreenState extends State<SiteTunnelsScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final double ipWidth = Utils.textSize("000.000.000.000", CupertinoTheme.of(context).textTheme.textStyle).width + 32; final double ipWidth = Utils.textSize("000.000.000.000", CupertinoTheme.of(context).textTheme.textStyle).width + 32;
final List<ConfigPageItem> children = tunnels.map((hostInfo) { final List<ConfigPageItem> children =
tunnels.map((hostInfo) {
final isLh = site.staticHostmap[hostInfo.vpnIp]?.lighthouse ?? false; final isLh = site.staticHostmap[hostInfo.vpnIp]?.lighthouse ?? false;
final icon = switch (isLh) { final icon = switch (isLh) {
true => Icon(Icons.lightbulb_outline, color: CupertinoColors.placeholderText.resolveFrom(context)), true => Icon(Icons.lightbulb_outline, color: CupertinoColors.placeholderText.resolveFrom(context)),
false => Icon(Icons.computer, color: CupertinoColors.placeholderText.resolveFrom(context)) false => Icon(Icons.computer, color: CupertinoColors.placeholderText.resolveFrom(context)),
}; };
return (ConfigPageItem( return (ConfigPageItem(
onPressed: () => Utils.openPage( onPressed:
() => Utils.openPage(
context, context,
(context) => HostInfoScreen( (context) => HostInfoScreen(
isLighthouse: isLh, isLighthouse: isLh,
@ -74,7 +76,9 @@ class _SiteTunnelsScreenState extends State<SiteTunnelsScreen> {
supportsQRScanning: widget.supportsQRScanning, supportsQRScanning: widget.supportsQRScanning,
), ),
), ),
label: Row(children: <Widget>[Padding(child: icon, padding: EdgeInsets.only(right: 10)), Text(hostInfo.vpnIp)]), label: Row(
children: <Widget>[Padding(child: icon, padding: EdgeInsets.only(right: 10)), Text(hostInfo.vpnIp)],
),
labelWidth: ipWidth, labelWidth: ipWidth,
content: Container(alignment: Alignment.centerRight, child: Text(hostInfo.cert?.details.name ?? "")), content: Container(alignment: Alignment.centerRight, child: Text(hostInfo.cert?.details.name ?? "")),
)); ));
@ -94,7 +98,8 @@ class _SiteTunnelsScreenState extends State<SiteTunnelsScreen> {
await _listHostmap(); await _listHostmap();
refreshController.refreshCompleted(); refreshController.refreshCompleted();
}, },
child: child); child: child,
);
} }
_sortTunnels() { _sortTunnels() {

View file

@ -98,21 +98,23 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
return ConfigButtonItem( return ConfigButtonItem(
content: Text('Share Public Key'), content: Text('Share Public Key'),
onPressed: () async { onPressed: () async {
await Share.share(context, await Share.share(
title: 'Please sign and return a certificate', text: pubKey, filename: 'device.pub'); context,
title: 'Please sign and return a certificate',
text: pubKey,
filename: 'device.pub',
);
}, },
); );
}, },
), ),
]) ],
),
]; ];
} }
List<Widget> _buildLoadCert() { List<Widget> _buildLoadCert() {
Map<String, Widget> children = { Map<String, Widget> children = {'paste': Text('Copy/Paste'), 'file': Text('File')};
'paste': Text('Copy/Paste'),
'file': Text('File'),
};
// not all devices have a camera for QR codes // not all devices have a camera for QR codes
if (widget.supportsQRScanning) { if (widget.supportsQRScanning) {
@ -132,7 +134,8 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
} }
}, },
children: children, children: children,
)) ),
),
]; ];
if (inputType == 'paste') { if (inputType == 'paste') {
@ -154,18 +157,20 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
width: double.infinity, width: double.infinity,
child: PrimaryButton( child: PrimaryButton(
child: Text('Show/Import Private Key'), child: Text('Show/Import Private Key'),
onPressed: () => Utils.confirmDelete(context, 'Show/Import Private Key?', () { onPressed:
() => Utils.confirmDelete(context, 'Show/Import Private Key?', () {
setState(() { setState(() {
showKey = true; showKey = true;
}); });
}, deleteLabel: 'Yes')))); }, deleteLabel: 'Yes'),
),
),
);
} }
return ConfigSection( return ConfigSection(
label: 'Import a private key generated on another device', label: 'Import a private key generated on another device',
children: [ children: [ConfigTextItem(controller: keyController, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14))],
ConfigTextItem(controller: keyController, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)),
],
); );
} }
@ -173,17 +178,15 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
return [ return [
ConfigSection( ConfigSection(
children: [ children: [
ConfigTextItem( ConfigTextItem(placeholder: 'Certificate PEM Contents', controller: pasteController),
placeholder: 'Certificate PEM Contents',
controller: pasteController,
),
ConfigButtonItem( ConfigButtonItem(
content: Center(child: Text('Load Certificate')), content: Center(child: Text('Load Certificate')),
onPressed: () { onPressed: () {
_addCertEntry(pasteController.text); _addCertEntry(pasteController.text);
}), },
),
], ],
) ),
]; ];
} }
@ -204,9 +207,10 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
} catch (err) { } catch (err) {
return Utils.popError(context, 'Failed to load certificate file', err.toString()); return Utils.popError(context, 'Failed to load certificate file', err.toString());
} }
}) },
),
], ],
) ),
]; ];
} }
@ -219,10 +223,7 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
onPressed: () async { onPressed: () async {
var result = await Navigator.push( var result = await Navigator.push(
context, context,
platformPageRoute( platformPageRoute(context: context, builder: (context) => new ScanQRScreen()),
context: context,
builder: (context) => new ScanQRScreen(),
),
); );
if (result != null) { if (result != null) {
_addCertEntry(result); _addCertEntry(result);
@ -230,7 +231,7 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
}, },
), ),
], ],
) ),
]; ];
} }
@ -247,18 +248,26 @@ class _AddCertificateScreenState extends State<AddCertificateScreen> {
if (certs.length > 0) { if (certs.length > 0) {
var tryCertInfo = CertificateInfo.fromJson(certs.first); var tryCertInfo = CertificateInfo.fromJson(certs.first);
if (tryCertInfo.cert.details.isCa) { if (tryCertInfo.cert.details.isCa) {
return Utils.popError(context, 'Error loading certificate content', return Utils.popError(
'A certificate authority is not appropriate for a client certificate.'); context,
'Error loading certificate content',
'A certificate authority is not appropriate for a client certificate.',
);
} else if (!tryCertInfo.validity!.valid) { } else if (!tryCertInfo.validity!.valid) {
return Utils.popError(context, 'Certificate was invalid', tryCertInfo.validity!.reason); return Utils.popError(context, 'Certificate was invalid', tryCertInfo.validity!.reason);
} }
var certMatch = await platform var certMatch = await platform.invokeMethod("nebula.verifyCertAndKey", <String, String>{
.invokeMethod("nebula.verifyCertAndKey", <String, String>{"cert": rawCert, "key": keyController.text}); "cert": rawCert,
"key": keyController.text,
});
if (!certMatch) { if (!certMatch) {
// The method above will throw if there is a mismatch, this is just here in case we introduce a bug in the future // The method above will throw if there is a mismatch, this is just here in case we introduce a bug in the future
return Utils.popError(context, 'Error loading certificate content', return Utils.popError(
'The provided certificates public key is not compatible with the private key.'); context,
'Error loading certificate content',
'The provided certificates public key is not compatible with the private key.',
);
} }
if (widget.onReplace != null) { if (widget.onReplace != null) {

View file

@ -40,11 +40,7 @@ class Advanced {
} }
class AdvancedScreen extends StatefulWidget { class AdvancedScreen extends StatefulWidget {
const AdvancedScreen({ const AdvancedScreen({Key? key, required this.site, required this.onSave}) : super(key: key);
Key? key,
required this.site,
required this.onSave,
}) : super(key: key);
final Site site; final Site site;
final ValueChanged<Advanced> onSave; final ValueChanged<Advanced> onSave;
@ -79,14 +75,16 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
Navigator.pop(context); Navigator.pop(context);
widget.onSave(settings); widget.onSave(settings);
}, },
child: Column(children: [ child: Column(
children: [
ConfigSection( ConfigSection(
children: [ children: [
ConfigItem( ConfigItem(
label: Text("Lighthouse interval"), label: Text("Lighthouse interval"),
labelWidth: 200, labelWidth: 200,
//TODO: Auto select on focus? //TODO: Auto select on focus?
content: widget.site.managed content:
widget.site.managed
? Text(settings.lhDuration.toString() + " seconds", textAlign: TextAlign.right) ? Text(settings.lhDuration.toString() + " seconds", textAlign: TextAlign.right)
: PlatformTextFormField( : PlatformTextFormField(
initialValue: settings.lhDuration.toString(), initialValue: settings.lhDuration.toString(),
@ -102,12 +100,14 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
} }
}); });
}, },
)), ),
),
ConfigItem( ConfigItem(
label: Text("Listen port"), label: Text("Listen port"),
labelWidth: 150, labelWidth: 150,
//TODO: Auto select on focus? //TODO: Auto select on focus?
content: widget.site.managed content:
widget.site.managed
? Text(settings.port.toString(), textAlign: TextAlign.right) ? Text(settings.port.toString(), textAlign: TextAlign.right)
: PlatformTextFormField( : PlatformTextFormField(
initialValue: settings.port.toString(), initialValue: settings.port.toString(),
@ -122,11 +122,13 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
} }
}); });
}, },
)), ),
),
ConfigItem( ConfigItem(
label: Text("MTU"), label: Text("MTU"),
labelWidth: 150, labelWidth: 150,
content: widget.site.managed content:
widget.site.managed
? Text(settings.mtu.toString(), textAlign: TextAlign.right) ? Text(settings.mtu.toString(), textAlign: TextAlign.right)
: PlatformTextFormField( : PlatformTextFormField(
initialValue: settings.mtu.toString(), initialValue: settings.mtu.toString(),
@ -141,7 +143,8 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
} }
}); });
}, },
)), ),
),
ConfigPageItem( ConfigPageItem(
disabled: widget.site.managed, disabled: widget.site.managed,
label: Text('Cipher'), label: Text('Cipher'),
@ -156,9 +159,11 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
settings.cipher = cipher; settings.cipher = cipher;
changed = true; changed = true;
}); });
},
);
}); });
}); },
}), ),
ConfigPageItem( ConfigPageItem(
disabled: widget.site.managed, disabled: widget.site.managed,
label: Text('Log verbosity'), label: Text('Log verbosity'),
@ -173,9 +178,11 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
settings.verbosity = verbosity; settings.verbosity = verbosity;
changed = true; changed = true;
}); });
},
);
}); });
}); },
}), ),
ConfigPageItem( ConfigPageItem(
label: Text('Unsafe routes'), label: Text('Unsafe routes'),
labelWidth: 150, labelWidth: 150,
@ -184,17 +191,19 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
Utils.openPage(context, (context) { Utils.openPage(context, (context) {
return UnsafeRoutesScreen( return UnsafeRoutesScreen(
unsafeRoutes: settings.unsafeRoutes, unsafeRoutes: settings.unsafeRoutes,
onSave: widget.site.managed onSave:
widget.site.managed
? null ? null
: (routes) { : (routes) {
setState(() { setState(() {
settings.unsafeRoutes = routes; settings.unsafeRoutes = routes;
changed = true; changed = true;
}); });
}); },
);
}); });
}, },
) ),
], ],
), ),
ConfigSection( ConfigSection(
@ -211,9 +220,11 @@ class _AdvancedScreenState extends State<AdvancedScreen> {
Utils.popError(context, 'Failed to render the site config', err.toString()); Utils.popError(context, 'Failed to render the site config', err.toString());
} }
}, },
) ),
], ],
) ),
])); ],
),
);
} }
} }

View file

@ -18,12 +18,7 @@ import 'package:mobile_nebula/services/utils.dart';
//TODO: In addition you will want to think about re-generation while the site is still active (This means storing multiple keys in secure storage) //TODO: In addition you will want to think about re-generation while the site is still active (This means storing multiple keys in secure storage)
class CAListScreen extends StatefulWidget { class CAListScreen extends StatefulWidget {
const CAListScreen({ const CAListScreen({Key? key, required this.cas, this.onSave, required this.supportsQRScanning}) : super(key: key);
Key? key,
required this.cas,
this.onSave,
required this.supportsQRScanning,
}) : super(key: key);
final List<CertificateInfo> cas; final List<CertificateInfo> cas;
final ValueChanged<List<CertificateInfo>>? onSave; final ValueChanged<List<CertificateInfo>>? onSave;
@ -70,24 +65,29 @@ class _CAListScreenState extends State<CAListScreen> {
onSave: () { onSave: () {
if (widget.onSave != null) { if (widget.onSave != null) {
Navigator.pop(context); Navigator.pop(context);
widget.onSave!(cas.values.map((ca) { widget.onSave!(
cas.values.map((ca) {
return ca; return ca;
}).toList()); }).toList(),
);
} }
}, },
child: Column(children: items)); child: Column(children: items),
);
} }
List<Widget> _buildCAs() { List<Widget> _buildCAs() {
List<Widget> items = []; List<Widget> items = [];
cas.forEach((key, ca) { cas.forEach((key, ca) {
items.add(ConfigPageItem( items.add(
ConfigPageItem(
content: Text(ca.cert.details.name), content: Text(ca.cert.details.name),
onPressed: () { onPressed: () {
Utils.openPage(context, (context) { Utils.openPage(context, (context) {
return CertificateDetailsScreen( return CertificateDetailsScreen(
certInfo: ca, certInfo: ca,
onDelete: widget.onSave == null onDelete:
widget.onSave == null
? null ? null
: () { : () {
setState(() { setState(() {
@ -99,7 +99,8 @@ class _CAListScreenState extends State<CAListScreen> {
); );
}); });
}, },
)); ),
);
}); });
return items; return items;
@ -137,10 +138,7 @@ class _CAListScreenState extends State<CAListScreen> {
} }
List<Widget> _addCA() { List<Widget> _addCA() {
Map<String, Widget> children = { Map<String, Widget> children = {'paste': Text('Copy/Paste'), 'file': Text('File')};
'paste': Text('Copy/Paste'),
'file': Text('File'),
};
// not all devices have a camera for QR codes // not all devices have a camera for QR codes
if (widget.supportsQRScanning) { if (widget.supportsQRScanning) {
@ -160,7 +158,8 @@ class _CAListScreenState extends State<CAListScreen> {
} }
}, },
children: children, children: children,
)) ),
),
]; ];
if (inputType == 'paste') { if (inputType == 'paste') {
@ -178,10 +177,7 @@ class _CAListScreenState extends State<CAListScreen> {
return [ return [
ConfigSection( ConfigSection(
children: [ children: [
ConfigTextItem( ConfigTextItem(placeholder: 'CA PEM contents', controller: pasteController),
placeholder: 'CA PEM contents',
controller: pasteController,
),
ConfigButtonItem( ConfigButtonItem(
content: Text('Load CA'), content: Text('Load CA'),
onPressed: () { onPressed: () {
@ -194,9 +190,10 @@ class _CAListScreenState extends State<CAListScreen> {
pasteController.text = ''; pasteController.text = '';
setState(() {}); setState(() {});
}); });
}), },
),
], ],
) ),
]; ];
} }
@ -223,9 +220,10 @@ class _CAListScreenState extends State<CAListScreen> {
} catch (err) { } catch (err) {
return Utils.popError(context, 'Failed to load CA file', err.toString()); return Utils.popError(context, 'Failed to load CA file', err.toString());
} }
}) },
),
], ],
) ),
]; ];
} }
@ -238,10 +236,7 @@ class _CAListScreenState extends State<CAListScreen> {
onPressed: () async { onPressed: () async {
var result = await Navigator.push( var result = await Navigator.push(
context, context,
platformPageRoute( platformPageRoute(context: context, builder: (context) => new ScanQRScreen()),
context: context,
builder: (context) => new ScanQRScreen(),
),
); );
if (result != null) { if (result != null) {
_addCAEntry(result, (err) { _addCAEntry(result, (err) {
@ -253,9 +248,9 @@ class _CAListScreenState extends State<CAListScreen> {
}); });
} }
}, },
) ),
], ],
) ),
]; ];
} }
} }

View file

@ -76,39 +76,44 @@ class _CertificateDetailsScreenState extends State<CertificateDetailsScreen> {
} }
}, },
hideSave: widget.onSave == null && widget.onReplace == null, hideSave: widget.onSave == null && widget.onReplace == null,
child: Column(children: [ child: Column(
_buildID(), children: [_buildID(), _buildFilters(), _buildValid(), _buildAdvanced(), _buildReplace(), _buildDelete()],
_buildFilters(), ),
_buildValid(),
_buildAdvanced(),
_buildReplace(),
_buildDelete(),
]),
); );
} }
Widget _buildID() { Widget _buildID() {
return ConfigSection(children: <Widget>[ return ConfigSection(
children: <Widget>[
ConfigItem(label: Text('Name'), content: SelectableText(certInfo.cert.details.name)), ConfigItem(label: Text('Name'), content: SelectableText(certInfo.cert.details.name)),
ConfigItem( ConfigItem(
label: Text('Type'), content: Text(certInfo.cert.details.isCa ? 'CA certificate' : 'Client certificate')), label: Text('Type'),
]); content: Text(certInfo.cert.details.isCa ? 'CA certificate' : 'Client certificate'),
),
],
);
} }
Widget _buildValid() { Widget _buildValid() {
var valid = Text('yes'); var valid = Text('yes');
if (certInfo.validity != null && !certInfo.validity!.valid) { if (certInfo.validity != null && !certInfo.validity!.valid) {
valid = Text(certInfo.validity!.valid ? 'yes' : certInfo.validity!.reason, valid = Text(
style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(context))); certInfo.validity!.valid ? 'yes' : certInfo.validity!.reason,
style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(context)),
);
} }
return ConfigSection( return ConfigSection(
label: 'VALIDITY', label: 'VALIDITY',
children: <Widget>[ children: <Widget>[
ConfigItem(label: Text('Valid?'), content: valid), ConfigItem(label: Text('Valid?'), content: valid),
ConfigItem( ConfigItem(
label: Text('Created'), content: SelectableText(certInfo.cert.details.notBefore.toLocal().toString())), label: Text('Created'),
content: SelectableText(certInfo.cert.details.notBefore.toLocal().toString()),
),
ConfigItem( ConfigItem(
label: Text('Expires'), content: SelectableText(certInfo.cert.details.notAfter.toLocal().toString())), label: Text('Expires'),
content: SelectableText(certInfo.cert.details.notAfter.toLocal().toString()),
),
], ],
); );
} }
@ -137,19 +142,23 @@ class _CertificateDetailsScreenState extends State<CertificateDetailsScreen> {
children: <Widget>[ children: <Widget>[
ConfigItem( ConfigItem(
label: Text('Fingerprint'), label: Text('Fingerprint'),
content: content: SelectableText(certInfo.cert.fingerprint, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)),
SelectableText(certInfo.cert.fingerprint, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start), ),
ConfigItem( ConfigItem(
label: Text('Public Key'), label: Text('Public Key'),
content: SelectableText(certInfo.cert.details.publicKey, content: SelectableText(
style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), certInfo.cert.details.publicKey,
crossAxisAlignment: CrossAxisAlignment.start), style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14),
),
crossAxisAlignment: CrossAxisAlignment.start,
),
certInfo.rawCert != null certInfo.rawCert != null
? ConfigItem( ? ConfigItem(
label: Text('PEM Format'), label: Text('PEM Format'),
content: SelectableText(certInfo.rawCert!, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), content: SelectableText(certInfo.rawCert!, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)),
crossAxisAlignment: CrossAxisAlignment.start) crossAxisAlignment: CrossAxisAlignment.start,
)
: Container(), : Container(),
], ],
); );
@ -176,15 +185,17 @@ class _CertificateDetailsScreenState extends State<CertificateDetailsScreen> {
certInfo = result.certInfo; certInfo = result.certInfo;
}); });
// Slam the page back to the top // Slam the page back to the top
controller.animateTo(0, controller.animateTo(0, duration: const Duration(milliseconds: 10), curve: Curves.linearToEaseOut);
duration: const Duration(milliseconds: 10), curve: Curves.linearToEaseOut);
}, },
pubKey: widget.pubKey!, pubKey: widget.pubKey!,
privKey: widget.privKey!, privKey: widget.privKey!,
supportsQRScanning: widget.supportsQRScanning, supportsQRScanning: widget.supportsQRScanning,
); );
}); });
}))); },
),
),
);
} }
Widget _buildDelete() { Widget _buildDelete() {
@ -200,9 +211,13 @@ class _CertificateDetailsScreenState extends State<CertificateDetailsScreen> {
width: double.infinity, width: double.infinity,
child: DangerButton( child: DangerButton(
child: Text('Delete'), child: Text('Delete'),
onPressed: () => Utils.confirmDelete(context, title, () async { onPressed:
() => Utils.confirmDelete(context, title, () async {
Navigator.pop(context); Navigator.pop(context);
widget.onDelete!(); widget.onDelete!();
})))); }),
),
),
);
} }
} }

View file

@ -6,11 +6,7 @@ import 'package:mobile_nebula/components/config/ConfigCheckboxItem.dart';
import 'package:mobile_nebula/components/config/ConfigSection.dart'; import 'package:mobile_nebula/components/config/ConfigSection.dart';
class CipherScreen extends StatefulWidget { class CipherScreen extends StatefulWidget {
const CipherScreen({ const CipherScreen({Key? key, required this.cipher, required this.onSave}) : super(key: key);
Key? key,
required this.cipher,
required this.onSave,
}) : super(key: key);
final String cipher; final String cipher;
final ValueChanged<String> onSave; final ValueChanged<String> onSave;
@ -40,7 +36,8 @@ class _CipherScreenState extends State<CipherScreen> {
}, },
child: Column( child: Column(
children: <Widget>[ children: <Widget>[
ConfigSection(children: [ ConfigSection(
children: [
ConfigCheckboxItem( ConfigCheckboxItem(
label: Text("aes"), label: Text("aes"),
labelWidth: 150, labelWidth: 150,
@ -62,9 +59,11 @@ class _CipherScreenState extends State<CipherScreen> {
cipher = "chachapoly"; cipher = "chachapoly";
}); });
}, },
) ),
])
], ],
)); ),
],
),
);
} }
} }

View file

@ -6,11 +6,7 @@ import 'package:mobile_nebula/components/config/ConfigCheckboxItem.dart';
import 'package:mobile_nebula/components/config/ConfigSection.dart'; import 'package:mobile_nebula/components/config/ConfigSection.dart';
class LogVerbosityScreen extends StatefulWidget { class LogVerbosityScreen extends StatefulWidget {
const LogVerbosityScreen({ const LogVerbosityScreen({Key? key, required this.verbosity, required this.onSave}) : super(key: key);
Key? key,
required this.verbosity,
required this.onSave,
}) : super(key: key);
final String verbosity; final String verbosity;
final ValueChanged<String> onSave; final ValueChanged<String> onSave;
@ -40,16 +36,19 @@ class _LogVerbosityScreenState extends State<LogVerbosityScreen> {
}, },
child: Column( child: Column(
children: <Widget>[ children: <Widget>[
ConfigSection(children: [ ConfigSection(
children: [
_buildEntry('debug'), _buildEntry('debug'),
_buildEntry('info'), _buildEntry('info'),
_buildEntry('warning'), _buildEntry('warning'),
_buildEntry('error'), _buildEntry('error'),
_buildEntry('fatal'), _buildEntry('fatal'),
_buildEntry('panic'), _buildEntry('panic'),
])
], ],
)); ),
],
),
);
} }
Widget _buildEntry(String title) { Widget _buildEntry(String title) {

View file

@ -7,11 +7,7 @@ class RenderedConfigScreen extends StatelessWidget {
final String config; final String config;
final String name; final String name;
RenderedConfigScreen({ RenderedConfigScreen({Key? key, required this.config, required this.name}) : super(key: key);
Key? key,
required this.config,
required this.name,
}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -19,18 +15,21 @@ class RenderedConfigScreen extends StatelessWidget {
title: Text('Rendered Site Config'), title: Text('Rendered Site Config'),
scrollable: SimpleScrollable.both, scrollable: SimpleScrollable.both,
trailingActions: <Widget>[ trailingActions: <Widget>[
Builder(builder: (BuildContext context) { Builder(
builder: (BuildContext context) {
return PlatformIconButton( return PlatformIconButton(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
icon: Icon(context.platformIcons.share, size: 28.0), icon: Icon(context.platformIcons.share, size: 28.0),
onPressed: () => Share.share(context, title: '$name.yaml', text: config, filename: '$name.yaml'), onPressed: () => Share.share(context, title: '$name.yaml', text: config, filename: '$name.yaml'),
); );
}), },
),
], ],
child: Container( child: Container(
padding: EdgeInsets.all(5), padding: EdgeInsets.all(5),
constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width), constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width),
child: SelectableText(config, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14))), child: SelectableText(config, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)),
),
); );
} }
} }

View file

@ -14,16 +14,14 @@ class _ScanQRScreenState extends State<ScanQRScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final scanWindow = Rect.fromCenter( final scanWindow = Rect.fromCenter(center: MediaQuery.sizeOf(context).center(Offset.zero), width: 250, height: 250);
center: MediaQuery.sizeOf(context).center(Offset.zero),
width: 250,
height: 250,
);
return Scaffold( return Scaffold(
appBar: AppBar(title: const Text('Scan QR')), appBar: AppBar(title: const Text('Scan QR')),
backgroundColor: Colors.black, backgroundColor: Colors.black,
body: Stack(fit: StackFit.expand, children: [ body: Stack(
fit: StackFit.expand,
children: [
Center( Center(
child: MobileScanner( child: MobileScanner(
fit: BoxFit.contain, fit: BoxFit.contain,
@ -36,7 +34,8 @@ class _ScanQRScreenState extends State<ScanQRScreen> {
Navigator.pop(context, barcode.rawValue); Navigator.pop(context, barcode.rawValue);
}); });
} }
}), },
),
), ),
ValueListenableBuilder( ValueListenableBuilder(
valueListenable: cameraController, valueListenable: cameraController,
@ -45,9 +44,7 @@ class _ScanQRScreenState extends State<ScanQRScreen> {
return const SizedBox(); return const SizedBox();
} }
return CustomPaint( return CustomPaint(painter: ScannerOverlay(scanWindow: scanWindow));
painter: ScannerOverlay(scanWindow: scanWindow),
);
}, },
), ),
Align( Align(
@ -63,15 +60,14 @@ class _ScanQRScreenState extends State<ScanQRScreen> {
), ),
), ),
), ),
])); ],
),
);
} }
} }
class ScannerOverlay extends CustomPainter { class ScannerOverlay extends CustomPainter {
const ScannerOverlay({ const ScannerOverlay({required this.scanWindow, this.borderRadius = 12.0});
required this.scanWindow,
this.borderRadius = 12.0,
});
final Rect scanWindow; final Rect scanWindow;
final double borderRadius; final double borderRadius;
@ -81,8 +77,8 @@ class ScannerOverlay extends CustomPainter {
// we need to pass the size to the custom paint widget // we need to pass the size to the custom paint widget
final backgroundPath = Path()..addRect(Rect.fromLTWH(0, 0, size.width, size.height)); final backgroundPath = Path()..addRect(Rect.fromLTWH(0, 0, size.width, size.height));
final cutoutPath = Path() final cutoutPath =
..addRRect( Path()..addRRect(
RRect.fromRectAndCorners( RRect.fromRectAndCorners(
scanWindow, scanWindow,
topLeft: Radius.circular(borderRadius), topLeft: Radius.circular(borderRadius),
@ -92,18 +88,16 @@ class ScannerOverlay extends CustomPainter {
), ),
); );
final backgroundPaint = Paint() final backgroundPaint =
Paint()
..color = Colors.black.withValues(alpha: 0.5) ..color = Colors.black.withValues(alpha: 0.5)
..style = PaintingStyle.fill ..style = PaintingStyle.fill
..blendMode = BlendMode.srcOver; ..blendMode = BlendMode.srcOver;
final backgroundWithCutout = Path.combine( final backgroundWithCutout = Path.combine(PathOperation.difference, backgroundPath, cutoutPath);
PathOperation.difference,
backgroundPath,
cutoutPath,
);
final borderPaint = Paint() final borderPaint =
Paint()
..color = Colors.white ..color = Colors.white
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 4.0; ..strokeWidth = 4.0;
@ -214,14 +208,7 @@ class ToggleFlashlightButton extends StatelessWidget {
}, },
); );
case TorchState.unavailable: case TorchState.unavailable:
return const SizedBox.square( return const SizedBox.square(dimension: 48.0, child: Icon(Icons.no_flash, size: 32.0, color: Colors.grey));
dimension: 48.0,
child: Icon(
Icons.no_flash,
size: 32.0,
color: Colors.grey,
),
);
} }
}, },
); );

View file

@ -23,12 +23,8 @@ import 'package:mobile_nebula/services/utils.dart';
//TODO: Enforce a name //TODO: Enforce a name
class SiteConfigScreen extends StatefulWidget { class SiteConfigScreen extends StatefulWidget {
const SiteConfigScreen({ const SiteConfigScreen({Key? key, this.site, required this.onSave, required this.supportsQRScanning})
Key? key, : super(key: key);
this.site,
required this.onSave,
required this.supportsQRScanning,
}) : super(key: key);
final Site? site; final Site? site;
@ -71,9 +67,11 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (pubKey == null || privKey == null) { if (pubKey == null || privKey == null) {
return Center( return Center(
child: fpw.PlatformCircularProgressIndicator(cupertino: (_, __) { child: fpw.PlatformCircularProgressIndicator(
cupertino: (_, __) {
return fpw.CupertinoProgressIndicatorData(radius: 50); return fpw.CupertinoProgressIndicatorData(radius: 50);
}), },
),
); );
} }
@ -100,7 +98,8 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
_managed(), _managed(),
kDebugMode ? _debugConfig() : Container(height: 0), kDebugMode ? _debugConfig() : Container(height: 0),
], ],
)); ),
);
} }
Widget _debugConfig() { Widget _debugConfig() {
@ -116,7 +115,8 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
} }
Widget _main() { Widget _main() {
return ConfigSection(children: <Widget>[ return ConfigSection(
children: <Widget>[
ConfigItem( ConfigItem(
label: Text("Name"), label: Text("Name"),
content: PlatformTextFormField( content: PlatformTextFormField(
@ -128,8 +128,10 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
} }
return null; return null;
}, },
)) ),
]); ),
],
);
} }
Widget _managed() { Widget _managed() {
@ -140,15 +142,19 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
} }
return site.managed return site.managed
? ConfigSection(label: "MANAGED CONFIG", children: <Widget>[ ? ConfigSection(
label: "MANAGED CONFIG",
children: <Widget>[
ConfigItem( ConfigItem(
label: Text("Last Update"), label: Text("Last Update"),
content: content: Wrap(
Wrap(alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, children: <Widget>[ alignment: WrapAlignment.end,
Text(lastUpdate), crossAxisAlignment: WrapCrossAlignment.center,
]), children: <Widget>[Text(lastUpdate)],
),
),
],
) )
])
: Container(); : Container();
} }
@ -171,14 +177,19 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
children: [ children: [
ConfigPageItem( ConfigPageItem(
label: Text('Certificate'), label: Text('Certificate'),
content: Wrap(alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, children: <Widget>[ content: Wrap(
alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
certError certError
? Padding( ? Padding(
child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20), child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20),
padding: EdgeInsets.only(right: 5)) padding: EdgeInsets.only(right: 5),
)
: Container(), : Container(),
certError ? Text('Needs attention') : Text(site.certInfo?.cert.details.name ?? 'Unknown certificate') certError ? Text('Needs attention') : Text(site.certInfo?.cert.details.name ?? 'Unknown certificate'),
]), ],
),
onPressed: () { onPressed: () {
Utils.openPage(context, (context) { Utils.openPage(context, (context) {
if (site.certInfo != null) { if (site.certInfo != null) {
@ -186,7 +197,8 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
certInfo: site.certInfo!, certInfo: site.certInfo!,
pubKey: pubKey, pubKey: pubKey,
privKey: privKey, privKey: privKey,
onReplace: site.managed onReplace:
site.managed
? null ? null
: (result) { : (result) {
setState(() { setState(() {
@ -216,20 +228,25 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
), ),
ConfigPageItem( ConfigPageItem(
label: Text("CA"), label: Text("CA"),
content: content: Wrap(
Wrap(alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, children: <Widget>[ alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
caError caError
? Padding( ? Padding(
child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20), child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20),
padding: EdgeInsets.only(right: 5)) padding: EdgeInsets.only(right: 5),
)
: Container(), : Container(),
caError ? Text('Needs attention') : Text(Utils.itemCountFormat(site.ca.length)) caError ? Text('Needs attention') : Text(Utils.itemCountFormat(site.ca.length)),
]), ],
),
onPressed: () { onPressed: () {
Utils.openPage(context, (context) { Utils.openPage(context, (context) {
return CAListScreen( return CAListScreen(
cas: site.ca, cas: site.ca,
onSave: site.managed onSave:
site.managed
? null ? null
: (ca) { : (ca) {
setState(() { setState(() {
@ -240,7 +257,8 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
supportsQRScanning: widget.supportsQRScanning, supportsQRScanning: widget.supportsQRScanning,
); );
}); });
}) },
),
], ],
); );
} }
@ -251,28 +269,35 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
children: <Widget>[ children: <Widget>[
ConfigPageItem( ConfigPageItem(
label: Text('Hosts'), label: Text('Hosts'),
content: Wrap(alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, children: <Widget>[ content: Wrap(
alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
site.staticHostmap.length == 0 site.staticHostmap.length == 0
? Padding( ? Padding(
child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20), child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20),
padding: EdgeInsets.only(right: 5)) padding: EdgeInsets.only(right: 5),
)
: Container(), : Container(),
site.staticHostmap.length == 0 site.staticHostmap.length == 0
? Text('Needs attention') ? Text('Needs attention')
: Text(Utils.itemCountFormat(site.staticHostmap.length)) : Text(Utils.itemCountFormat(site.staticHostmap.length)),
]), ],
),
onPressed: () { onPressed: () {
Utils.openPage(context, (context) { Utils.openPage(context, (context) {
return StaticHostsScreen( return StaticHostsScreen(
hostmap: site.staticHostmap, hostmap: site.staticHostmap,
onSave: site.managed onSave:
site.managed
? null ? null
: (map) { : (map) {
setState(() { setState(() {
changed = true; changed = true;
site.staticHostmap = map; site.staticHostmap = map;
}); });
}); },
);
}); });
}, },
), ),
@ -300,9 +325,11 @@ class _SiteConfigScreenState extends State<SiteConfigScreen> {
site.unsafeRoutes = settings.unsafeRoutes; site.unsafeRoutes = settings.unsafeRoutes;
site.mtu = settings.mtu; site.mtu = settings.mtu;
}); });
},
);
}); });
}); },
}) ),
], ],
); );
} }

View file

@ -67,19 +67,24 @@ class _StaticHostmapScreenState extends State<StaticHostmapScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return FormPage( return FormPage(
title: widget.onDelete == null title:
widget.onDelete == null
? widget.onSave == null ? widget.onSave == null
? 'View Static Host' ? 'View Static Host'
: 'New Static Host' : 'New Static Host'
: 'Edit Static Host', : 'Edit Static Host',
changed: changed, changed: changed,
onSave: _onSave, onSave: _onSave,
child: Column(children: [ child: Column(
ConfigSection(label: 'Maps a nebula ip address to multiple real world addresses', children: <Widget>[ children: [
ConfigSection(
label: 'Maps a nebula ip address to multiple real world addresses',
children: <Widget>[
ConfigItem( ConfigItem(
label: Text('Nebula IP'), label: Text('Nebula IP'),
labelWidth: 200, labelWidth: 200,
content: widget.onSave == null content:
widget.onSave == null
? Text(_nebulaIp, textAlign: TextAlign.end) ? Text(_nebulaIp, textAlign: TextAlign.end)
: IPFormField( : IPFormField(
help: "Required", help: "Required",
@ -92,7 +97,9 @@ class _StaticHostmapScreenState extends State<StaticHostmapScreen> {
if (v != null) { if (v != null) {
_nebulaIp = v; _nebulaIp = v;
} }
})), },
),
),
ConfigItem( ConfigItem(
label: Text('Lighthouse'), label: Text('Lighthouse'),
labelWidth: 200, labelWidth: 200,
@ -101,20 +108,21 @@ class _StaticHostmapScreenState extends State<StaticHostmapScreen> {
child: Switch.adaptive( child: Switch.adaptive(
value: _lighthouse, value: _lighthouse,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
onChanged: widget.onSave == null onChanged:
widget.onSave == null
? null ? null
: (v) { : (v) {
setState(() { setState(() {
changed = true; changed = true;
_lighthouse = v; _lighthouse = v;
}); });
})), },
), ),
]),
ConfigSection(
label: 'List of public ips or dns names where for this host',
children: _buildHosts(),
), ),
),
],
),
ConfigSection(label: 'List of public ips or dns names where for this host', children: _buildHosts()),
widget.onDelete != null widget.onDelete != null
? Padding( ? Padding(
padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10), padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10),
@ -122,12 +130,18 @@ class _StaticHostmapScreenState extends State<StaticHostmapScreen> {
width: double.infinity, width: double.infinity,
child: DangerButton( child: DangerButton(
child: Text('Delete'), child: Text('Delete'),
onPressed: () => Utils.confirmDelete(context, 'Delete host map?', () { onPressed:
() => Utils.confirmDelete(context, 'Delete host map?', () {
Navigator.of(context).pop(); Navigator.of(context).pop();
widget.onDelete!(); widget.onDelete!();
})))) }),
: Container() ),
])); ),
)
: Container(),
],
),
);
} }
_onSave() { _onSave() {
@ -147,23 +161,30 @@ class _StaticHostmapScreenState extends State<StaticHostmapScreen> {
List<Widget> items = []; List<Widget> items = [];
_destinations.forEach((key, dest) { _destinations.forEach((key, dest) {
items.add(ConfigItem( items.add(
ConfigItem(
key: key, key: key,
label: Align( label: Align(
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
child: widget.onSave == null child:
widget.onSave == null
? Container() ? Container()
: PlatformIconButton( : PlatformIconButton(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
icon: Icon(Icons.remove_circle, color: CupertinoColors.systemRed.resolveFrom(context)), icon: Icon(Icons.remove_circle, color: CupertinoColors.systemRed.resolveFrom(context)),
onPressed: () => setState(() { onPressed:
() => setState(() {
_removeDestination(key); _removeDestination(key);
_dismissKeyboard(); _dismissKeyboard();
}))), }),
),
),
labelWidth: 70, labelWidth: 70,
content: Row(children: <Widget>[ content: Row(
children: <Widget>[
Expanded( Expanded(
child: widget.onSave == null child:
widget.onSave == null
? Text(dest.destination.toString(), textAlign: TextAlign.end) ? Text(dest.destination.toString(), textAlign: TextAlign.end)
: IPAndPortFormField( : IPAndPortFormField(
ipHelp: 'public ip or name', ipHelp: 'public ip or name',
@ -176,18 +197,25 @@ class _StaticHostmapScreenState extends State<StaticHostmapScreen> {
dest.destination = v; dest.destination = v;
} }
}, },
)), ),
]), ),
)); ],
),
),
);
}); });
if (widget.onSave != null) { if (widget.onSave != null) {
items.add(ConfigButtonItem( items.add(
ConfigButtonItem(
content: Text('Add another'), content: Text('Add another'),
onPressed: () => setState(() { onPressed:
() => setState(() {
_addDestination(); _addDestination();
_dismissKeyboard(); _dismissKeyboard();
}))); }),
),
);
} }
return items; return items;

View file

@ -18,20 +18,11 @@ class _Hostmap {
List<IPAndPort> destinations; List<IPAndPort> destinations;
bool lighthouse; bool lighthouse;
_Hostmap({ _Hostmap({required this.focusNode, required this.nebulaIp, required this.destinations, required this.lighthouse});
required this.focusNode,
required this.nebulaIp,
required this.destinations,
required this.lighthouse,
});
} }
class StaticHostsScreen extends StatefulWidget { class StaticHostsScreen extends StatefulWidget {
const StaticHostsScreen({ const StaticHostsScreen({Key? key, required this.hostmap, required this.onSave}) : super(key: key);
Key? key,
required this.hostmap,
required this.onSave,
}) : super(key: key);
final Map<String, StaticHost> hostmap; final Map<String, StaticHost> hostmap;
final ValueChanged<Map<String, StaticHost>>? onSave; final ValueChanged<Map<String, StaticHost>>? onSave;
@ -47,8 +38,12 @@ class _StaticHostsScreenState extends State<StaticHostsScreen> {
@override @override
void initState() { void initState() {
widget.hostmap.forEach((key, map) { widget.hostmap.forEach((key, map) {
_hostmap[UniqueKey()] = _hostmap[UniqueKey()] = _Hostmap(
_Hostmap(focusNode: FocusNode(), nebulaIp: key, destinations: map.destinations, lighthouse: map.lighthouse); focusNode: FocusNode(),
nebulaIp: key,
destinations: map.destinations,
lighthouse: map.lighthouse,
);
}); });
super.initState(); super.initState();
@ -60,9 +55,8 @@ class _StaticHostsScreenState extends State<StaticHostsScreen> {
title: 'Static Hosts', title: 'Static Hosts',
changed: changed, changed: changed,
onSave: _onSave, onSave: _onSave,
child: ConfigSection( child: ConfigSection(children: _buildHosts()),
children: _buildHosts(), );
));
} }
_onSave() { _onSave() {
@ -81,14 +75,20 @@ class _StaticHostsScreenState extends State<StaticHostsScreen> {
final double ipWidth = Utils.textSize("000.000.000.000", CupertinoTheme.of(context).textTheme.textStyle).width + 32; final double ipWidth = Utils.textSize("000.000.000.000", CupertinoTheme.of(context).textTheme.textStyle).width + 32;
List<Widget> items = []; List<Widget> items = [];
_hostmap.forEach((key, host) { _hostmap.forEach((key, host) {
items.add(ConfigPageItem( items.add(
label: Row(children: <Widget>[ ConfigPageItem(
label: Row(
children: <Widget>[
Padding( Padding(
child: Icon(host.lighthouse ? Icons.lightbulb_outline : Icons.computer, child: Icon(
color: CupertinoColors.placeholderText.resolveFrom(context)), host.lighthouse ? Icons.lightbulb_outline : Icons.computer,
padding: EdgeInsets.only(right: 10)), color: CupertinoColors.placeholderText.resolveFrom(context),
),
padding: EdgeInsets.only(right: 10),
),
Text(host.nebulaIp), Text(host.nebulaIp),
]), ],
),
labelWidth: ipWidth, labelWidth: ipWidth,
content: Text(host.destinations.length.toString() + ' items', textAlign: TextAlign.end), content: Text(host.destinations.length.toString() + ' items', textAlign: TextAlign.end),
onPressed: () { onPressed: () {
@ -97,7 +97,8 @@ class _StaticHostsScreenState extends State<StaticHostsScreen> {
nebulaIp: host.nebulaIp, nebulaIp: host.nebulaIp,
destinations: host.destinations, destinations: host.destinations,
lighthouse: host.lighthouse, lighthouse: host.lighthouse,
onSave: widget.onSave == null onSave:
widget.onSave == null
? null ? null
: (map) { : (map) {
setState(() { setState(() {
@ -107,33 +108,40 @@ class _StaticHostsScreenState extends State<StaticHostsScreen> {
host.lighthouse = map.lighthouse; host.lighthouse = map.lighthouse;
}); });
}, },
onDelete: widget.onSave == null onDelete:
widget.onSave == null
? null ? null
: () { : () {
setState(() { setState(() {
changed = true; changed = true;
_hostmap.remove(key); _hostmap.remove(key);
}); });
}); },
);
}); });
}, },
)); ),
);
}); });
if (widget.onSave != null) { if (widget.onSave != null) {
items.add(ConfigButtonItem( items.add(
ConfigButtonItem(
content: Text('Add a new entry'), content: Text('Add a new entry'),
onPressed: () { onPressed: () {
Utils.openPage(context, (context) { Utils.openPage(context, (context) {
return StaticHostmapScreen(onSave: (map) { return StaticHostmapScreen(
onSave: (map) {
setState(() { setState(() {
changed = true; changed = true;
_addHostmap(map); _addHostmap(map);
}); });
}); },
);
}); });
}, },
)); ),
);
} }
return items; return items;
@ -141,7 +149,11 @@ class _StaticHostsScreenState extends State<StaticHostsScreen> {
_addHostmap(Hostmap map) { _addHostmap(Hostmap map) {
_hostmap[UniqueKey()] = (_Hostmap( _hostmap[UniqueKey()] = (_Hostmap(
focusNode: FocusNode(), nebulaIp: map.nebulaIp, destinations: map.destinations, lighthouse: map.lighthouse)); focusNode: FocusNode(),
nebulaIp: map.nebulaIp,
destinations: map.destinations,
lighthouse: map.lighthouse,
));
} }
@override @override

View file

@ -10,12 +10,7 @@ import 'package:mobile_nebula/models/UnsafeRoute.dart';
import 'package:mobile_nebula/services/utils.dart'; import 'package:mobile_nebula/services/utils.dart';
class UnsafeRouteScreen extends StatefulWidget { class UnsafeRouteScreen extends StatefulWidget {
const UnsafeRouteScreen({ const UnsafeRouteScreen({Key? key, required this.route, required this.onSave, this.onDelete}) : super(key: key);
Key? key,
required this.route,
required this.onSave,
this.onDelete,
}) : super(key: key);
final UnsafeRoute route; final UnsafeRoute route;
final ValueChanged<UnsafeRoute> onSave; final ValueChanged<UnsafeRoute> onSave;
@ -47,8 +42,10 @@ class _UnsafeRouteScreenState extends State<UnsafeRouteScreen> {
title: widget.onDelete == null ? 'New Unsafe Route' : 'Edit Unsafe Route', title: widget.onDelete == null ? 'New Unsafe Route' : 'Edit Unsafe Route',
changed: changed, changed: changed,
onSave: _onSave, onSave: _onSave,
child: Column(children: [ child: Column(
ConfigSection(children: <Widget>[ children: [
ConfigSection(
children: <Widget>[
ConfigItem( ConfigItem(
label: Text('Route'), label: Text('Route'),
content: CIDRFormField( content: CIDRFormField(
@ -58,7 +55,9 @@ class _UnsafeRouteScreenState extends State<UnsafeRouteScreen> {
nextFocusNode: viaFocus, nextFocusNode: viaFocus,
onSaved: (v) { onSaved: (v) {
route.route = v.toString(); route.route = v.toString();
})), },
),
),
ConfigItem( ConfigItem(
label: Text('Via'), label: Text('Via'),
content: IPFormField( content: IPFormField(
@ -74,23 +73,26 @@ class _UnsafeRouteScreenState extends State<UnsafeRouteScreen> {
if (v != null) { if (v != null) {
route.via = v; route.via = v;
} }
})), },
//TODO: Android doesn't appear to support route based MTU, figure this out ),
// ConfigItem( ),
// label: Text('MTU'), //TODO: Android doesn't appear to support route based MTU, figure this out
// content: PlatformTextFormField( // ConfigItem(
// placeholder: "", // label: Text('MTU'),
// validator: mtuValidator(false), // content: PlatformTextFormField(
// keyboardType: TextInputType.number, // placeholder: "",
// inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], // validator: mtuValidator(false),
// initialValue: route?.mtu.toString(), // keyboardType: TextInputType.number,
// textAlign: TextAlign.end, // inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
// textInputAction: TextInputAction.done, // initialValue: route?.mtu.toString(),
// focusNode: mtuFocus, // textAlign: TextAlign.end,
// onSaved: (v) { // textInputAction: TextInputAction.done,
// route.mtu = int.tryParse(v); // focusNode: mtuFocus,
// })), // onSaved: (v) {
]), // route.mtu = int.tryParse(v);
// })),
],
),
widget.onDelete != null widget.onDelete != null
? Padding( ? Padding(
padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10), padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10),
@ -98,13 +100,18 @@ class _UnsafeRouteScreenState extends State<UnsafeRouteScreen> {
width: double.infinity, width: double.infinity,
child: DangerButton( child: DangerButton(
child: Text('Delete'), child: Text('Delete'),
onPressed: () => Utils.confirmDelete(context, 'Delete unsafe route?', () { onPressed:
() => Utils.confirmDelete(context, 'Delete unsafe route?', () {
Navigator.of(context).pop(); Navigator.of(context).pop();
widget.onDelete!(); widget.onDelete!();
}), }),
))) ),
: Container() ),
])); )
: Container(),
],
),
);
} }
_onSave() { _onSave() {

View file

@ -8,11 +8,7 @@ import 'package:mobile_nebula/screens/siteConfig/UnsafeRouteScreen.dart';
import 'package:mobile_nebula/services/utils.dart'; import 'package:mobile_nebula/services/utils.dart';
class UnsafeRoutesScreen extends StatefulWidget { class UnsafeRoutesScreen extends StatefulWidget {
const UnsafeRoutesScreen({ const UnsafeRoutesScreen({Key? key, required this.unsafeRoutes, required this.onSave}) : super(key: key);
Key? key,
required this.unsafeRoutes,
required this.onSave,
}) : super(key: key);
final List<UnsafeRoute> unsafeRoutes; final List<UnsafeRoute> unsafeRoutes;
final ValueChanged<List<UnsafeRoute>>? onSave; final ValueChanged<List<UnsafeRoute>>? onSave;
@ -41,9 +37,8 @@ class _UnsafeRoutesScreenState extends State<UnsafeRoutesScreen> {
title: 'Unsafe Routes', title: 'Unsafe Routes',
changed: changed, changed: changed,
onSave: _onSave, onSave: _onSave,
child: ConfigSection( child: ConfigSection(children: _buildRoutes()),
children: _buildRoutes(), );
));
} }
_onSave() { _onSave() {
@ -57,7 +52,8 @@ class _UnsafeRoutesScreenState extends State<UnsafeRoutesScreen> {
final double ipWidth = Utils.textSize("000.000.000.000/00", CupertinoTheme.of(context).textTheme.textStyle).width; final double ipWidth = Utils.textSize("000.000.000.000/00", CupertinoTheme.of(context).textTheme.textStyle).width;
List<Widget> items = []; List<Widget> items = [];
unsafeRoutes.forEach((key, route) { unsafeRoutes.forEach((key, route) {
items.add(ConfigPageItem( items.add(
ConfigPageItem(
disabled: widget.onSave == null, disabled: widget.onSave == null,
label: Text(route.route ?? ''), label: Text(route.route ?? ''),
labelWidth: ipWidth, labelWidth: ipWidth,
@ -77,14 +73,17 @@ class _UnsafeRoutesScreenState extends State<UnsafeRoutesScreen> {
changed = true; changed = true;
unsafeRoutes.remove(key); unsafeRoutes.remove(key);
}); });
}); },
);
}); });
}, },
)); ),
);
}); });
if (widget.onSave != null) { if (widget.onSave != null) {
items.add(ConfigButtonItem( items.add(
ConfigButtonItem(
content: Text('Add a new route'), content: Text('Add a new route'),
onPressed: () { onPressed: () {
Utils.openPage(context, (context) { Utils.openPage(context, (context) {
@ -95,10 +94,12 @@ class _UnsafeRoutesScreenState extends State<UnsafeRoutesScreen> {
changed = true; changed = true;
unsafeRoutes[UniqueKey()] = route; unsafeRoutes[UniqueKey()] = route;
}); });
}); },
);
}); });
}, },
)); ),
);
} }
return items; return items;

View file

@ -40,8 +40,12 @@ class Share {
/// - title: Title of message or subject if sending an email /// - title: Title of message or subject if sending an email
/// - filePath: Path to the file to share /// - filePath: Path to the file to share
/// - filename: An optional filename to override the existing file /// - filename: An optional filename to override the existing file
static Future<bool> shareFile(BuildContext context, static Future<bool> shareFile(
{required String title, required String filePath, String? filename}) async { BuildContext context, {
required String title,
required String filePath,
String? filename,
}) async {
assert(title.isNotEmpty); assert(title.isNotEmpty);
assert(filePath.isNotEmpty); assert(filePath.isNotEmpty);
@ -51,8 +55,11 @@ class Share {
// If we want to support that again we will need to save the file to a temporary directory, share that, // If we want to support that again we will need to save the file to a temporary directory, share that,
// and then delete it // and then delete it
final xFile = sp.XFile(filePath, name: filename); final xFile = sp.XFile(filePath, name: filename);
final result = await sp.Share.shareXFiles([xFile], final result = await sp.Share.shareXFiles(
subject: title, sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size); [xFile],
subject: title,
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
);
return result.status == sp.ShareResultStatus.success; return result.status == sp.ShareResultStatus.success;
} }
} }

View file

@ -20,9 +20,12 @@ class Storage {
var completer = Completer<List<FileSystemEntity>>(); var completer = Completer<List<FileSystemEntity>>();
Directory(parent).list().listen((FileSystemEntity entity) { Directory(parent)
.list()
.listen((FileSystemEntity entity) {
list.add(entity); list.add(entity);
}).onDone(() { })
.onDone(() {
completer.complete(list); completer.complete(list);
}); });

View file

@ -342,10 +342,7 @@ class MaterialTheme {
useMaterial3: true, useMaterial3: true,
brightness: colorScheme.brightness, brightness: colorScheme.brightness,
colorScheme: colorScheme, colorScheme: colorScheme,
textTheme: textTheme.apply( textTheme: textTheme.apply(bodyColor: colorScheme.onSurface, displayColor: colorScheme.onSurface),
bodyColor: colorScheme.onSurface,
displayColor: colorScheme.onSurface,
),
scaffoldBackgroundColor: colorScheme.surface, scaffoldBackgroundColor: colorScheme.surface,
canvasColor: colorScheme.surface, canvasColor: colorScheme.surface,
); );

View file

@ -27,20 +27,16 @@ class Utils {
} }
static Size textSize(String text, TextStyle style) { static Size textSize(String text, TextStyle style) {
final TextPainter textPainter = final TextPainter textPainter = TextPainter(
TextPainter(text: TextSpan(text: text, style: style), maxLines: 1, textDirection: TextDirection.ltr) text: TextSpan(text: text, style: style),
..layout(minWidth: 0, maxWidth: double.infinity); maxLines: 1,
textDirection: TextDirection.ltr,
)..layout(minWidth: 0, maxWidth: double.infinity);
return textPainter.size; return textPainter.size;
} }
static openPage(BuildContext context, WidgetBuilder pageToDisplayBuilder) { static openPage(BuildContext context, WidgetBuilder pageToDisplayBuilder) {
Navigator.push( Navigator.push(context, platformPageRoute(context: context, builder: pageToDisplayBuilder));
context,
platformPageRoute(
context: context,
builder: pageToDisplayBuilder,
),
);
} }
static String itemCountFormat(int items, {singleSuffix = "item", multiSuffix = "items"}) { static String itemCountFormat(int items, {singleSuffix = "item", multiSuffix = "items"}) {
@ -63,7 +59,8 @@ class Utils {
} else { } else {
onPressed(); onPressed();
} }
}); },
);
} }
return IconButton( return IconButton(
@ -82,12 +79,20 @@ class Utils {
static Widget trailingSaveWidget(BuildContext context, Function onPressed) { static Widget trailingSaveWidget(BuildContext context, Function onPressed) {
return PlatformTextButton( return PlatformTextButton(
child: Text('Save'), padding: Platform.isAndroid ? null : EdgeInsets.zero, onPressed: () => onPressed()); child: Text('Save'),
padding: Platform.isAndroid ? null : EdgeInsets.zero,
onPressed: () => onPressed(),
);
} }
/// Simple cross platform delete confirmation dialog - can also be used to confirm throwing away a change by swapping the deleteLabel /// Simple cross platform delete confirmation dialog - can also be used to confirm throwing away a change by swapping the deleteLabel
static confirmDelete(BuildContext context, String title, Function onConfirm, static confirmDelete(
{String deleteLabel = 'Delete', String cancelLabel = 'Cancel'}) { BuildContext context,
String title,
Function onConfirm, {
String deleteLabel = 'Delete',
String cancelLabel = 'Cancel',
}) {
showDialog<void>( showDialog<void>(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
@ -96,9 +101,10 @@ class Utils {
title: Text(title), title: Text(title),
actions: <Widget>[ actions: <Widget>[
PlatformDialogAction( PlatformDialogAction(
child: Text(deleteLabel, child: Text(
style: deleteLabel,
TextStyle(fontWeight: FontWeight.bold, color: CupertinoColors.systemRed.resolveFrom(context))), style: TextStyle(fontWeight: FontWeight.bold, color: CupertinoColors.systemRed.resolveFrom(context)),
),
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
onConfirm(); onConfirm();
@ -109,10 +115,11 @@ class Utils {
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
) ),
], ],
); );
}); },
);
} }
static popError(BuildContext context, String title, String error, {StackTrace? stack}) { static popError(BuildContext context, String title, String error, {StackTrace? stack}) {
@ -125,14 +132,18 @@ class Utils {
barrierDismissible: false, barrierDismissible: false,
builder: (context) { builder: (context) {
if (Platform.isAndroid) { if (Platform.isAndroid) {
return AlertDialog(title: Text(title), content: Text(error), actions: <Widget>[ return AlertDialog(
title: Text(title),
content: Text(error),
actions: <Widget>[
TextButton( TextButton(
child: Text('Ok'), child: Text('Ok'),
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
) ),
]); ],
);
} }
return CupertinoAlertDialog( return CupertinoAlertDialog(
@ -144,10 +155,11 @@ class Utils {
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
) ),
], ],
); );
}); },
);
} }
static launchUrl(String url, BuildContext context) async { static launchUrl(String url, BuildContext context) async {