file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
lib/src/hover_builder.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; typedef HoverWidgetBuilder = Widget Function(BuildContext context, bool hover); class HoverBuilder extends StatefulWidget { const HoverBuilder({ Key? key, required this.builder, this.cursor = MouseCursor.defer, }) : super(key: key); final HoverWidgetBuilder builder; final MouseCursor cursor; @override _HoverBuilderState createState() => _HoverBuilderState(); } class _HoverBuilderState extends State<HoverBuilder> { bool hover = false; @override Widget build(BuildContext context) { return MouseRegion( onEnter: (PointerEnterEvent event) => setState(() => hover = true), onExit: (PointerExitEvent event) => setState(() => hover = false), cursor: widget.cursor, child: widget.builder(context, hover), ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/indexed_offset.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/foundation.dart'; @immutable class IndexedOffset with Diagnosticable { const IndexedOffset(this.rowIndex, this.columnIndex); final int rowIndex; final int columnIndex; @override int get hashCode => Object.hash(rowIndex, columnIndex); @override bool operator ==(Object other) { if (identical(this, other)) return true; if (runtimeType != other.runtimeType) return false; return other is IndexedOffset && other.rowIndex == rowIndex && other.columnIndex == columnIndex; } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('rowIndex', rowIndex)); properties.add(IntProperty('columnIndex', columnIndex)); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/link_button.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/widgets.dart'; import 'action_tracker.dart'; import 'hover_builder.dart'; class LinkButton extends StatelessWidget { const LinkButton({Key? key, this.image, required this.text, this.onPressed}) : super(key: key); final ImageProvider? image; final String text; final VoidCallback? onPressed; Widget _buildContent({required Color color, bool hover = false}) { Widget? imageWidget; if (image != null) { imageWidget = Padding( padding: EdgeInsets.only(right: 4), child: Image(image: image!), ); if (onPressed == null) { imageWidget = Opacity(opacity: 0.5, child: imageWidget); } } Widget link = Padding( padding: const EdgeInsets.only(bottom: 1), child: Text(text, style: TextStyle(color: color)), ); if (hover) { link = DecoratedBox( decoration: BoxDecoration( border: Border(bottom: BorderSide(color: color)), ), child: link, ); } return Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[if (imageWidget != null) imageWidget, link], ); } @override Widget build(BuildContext context) { if (onPressed == null) { return _buildContent(color: const Color(0xff999999)); } else { return Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ HoverBuilder( cursor: SystemMouseCursors.click, builder: (BuildContext context, bool hover) { return GestureDetector( onTap: onPressed, child: _buildContent( color: const Color(0xff2b5580), hover: hover, ), ); }, ), ], ); } } } class ActionLinkButton<I extends Intent> extends ActionTracker<I> { const ActionLinkButton({ Key? key, required I intent, ValueChanged<Object?>? onActionInvoked, this.image, required this.text, }) : super(key: key, intent: intent, onActionInvoked: onActionInvoked); final ImageProvider? image; final String text; @override _ActionLinkButtonState<I> createState() => _ActionLinkButtonState<I>(); } class _ActionLinkButtonState<I extends Intent> extends State<ActionLinkButton<I>> with ActionTrackerStateMixin<I, ActionLinkButton<I>> { @override Widget build(BuildContext context) { return LinkButton( text: widget.text, image: widget.image, onPressed: isEnabled ? invokeAction : null, ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/list_button.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'basic_list_view.dart'; import 'foundation.dart'; import 'list_view.dart'; import 'widget_surveyor.dart'; /// Enum that specifies how a [ListButton] will calculate its width. enum ListButtonWidth { /// Specification of [ListButton] width that causes the button to adopt the /// intrinsic width of the currently selected item. /// /// This specification will cause the button width to change as different /// items are selected, if those items have different intrinsic widths. /// /// Along with [expand], this specification is the fastest in runtime /// efficiency because it doesn't need to pre-calculate the intrinsic widths /// of the list button's items. shrinkWrapCurrentItem, /// Specification of [ListButton] width that causes the button to adopt the /// largest intrinsic width of _all_ the button's items. /// /// This specification will yield a stable button width. As the selected item /// changes, the button width will always be at least as wide as it needs to /// be, sometimes wider. /// /// This specification is relatively expensive in runtime efficiency, because /// it requires pre-calculating the unconstrained widths of the list button's /// items. /// /// This will cause the list button's [ListButton.builder] to be invoked for /// every one of the button's list items in order to measure their widths. /// The list button element will be passed as the build context. When this /// measurement is taken, the widgets will be rendered in a synthetic widget /// tree that doesn't contain the normal application widget ancestry. If any /// of those widgets depend on inherited widgets in their ancestry, this /// measurement will fail. shrinkWrapAllItems, /// Specification of [ListButton] width that causes the button to adopt the /// widest possible width given the constraints passed to the list button. /// /// This specification will cause the button width to remain stable as long /// as the input constraints remain stable. /// /// Along with [shrinkWrapCurrentItem], this specification is the fastest in /// runtime efficiency because it doesn't need to pre-calculate the intrinsic /// widths of the list button's items. expand, } typedef ListButtonBuilder<T> = Widget Function(BuildContext context, T? item, bool isForMeasurementOnly); typedef ListButtonItemBuilder<T> = Widget Function( BuildContext context, T item, bool isSelected, bool isHighlighted, bool isDisabled, ); class ListButton<T> extends StatefulWidget { ListButton({ Key? key, required this.items, this.builder = defaultBuilder, this.itemBuilder = defaultItemBuilder, this.width = ListButtonWidth.shrinkWrapCurrentItem, this.selectionController, this.disabledItemFilter, this.isEnabled = true, this.roundToWholePixel = false, }) : assert( selectionController == null || selectionController.selectMode == SelectMode.single, ), super(key: key); final List<T> items; final ListButtonBuilder<T> builder; final ListButtonItemBuilder<T> itemBuilder; final ListButtonWidth width; final ListViewSelectionController? selectionController; final Predicate<T>? disabledItemFilter; final bool isEnabled; final bool roundToWholePixel; static Widget defaultBuilder( BuildContext context, Object? item, bool isForMeasurementOnly, ) { if (item == null) { return Container(); } final TextStyle style = DefaultTextStyle.of(context).style; final TextDirection textDirection = Directionality.of(context); return Padding( padding: EdgeInsets.only(bottom: 1), child: Text( '$item', maxLines: 1, softWrap: false, textDirection: textDirection, style: style, ), ); } static Widget defaultItemBuilder( BuildContext context, Object? item, bool isSelected, bool isHighlighted, bool isDisabled, ) { TextStyle style = DefaultTextStyle.of(context).style; if (isSelected) { style = style.copyWith(color: const Color(0xffffffff)); } if (isDisabled) { style = style.copyWith(color: const Color(0xff999999)); } return ConstrainedBox( constraints: BoxConstraints(minWidth: 75), child: Padding( padding: EdgeInsets.symmetric(horizontal: 3, vertical: 2), child: Text('$item', style: style), ), ); } static ListButtonBuilder<Map<K, V>> mapBuilderFor<K, V>(K key) { return (BuildContext context, Map<K, V>? item, bool isForMeasurementOnly) { return defaultBuilder( context, item == null ? null : item[key], isForMeasurementOnly, ); }; } static ListButtonItemBuilder<Map<K, V>> mapItemBuilderFor<K, V>(K key) { return ( BuildContext context, Map<K, V> item, bool isSelected, bool isHighlighted, bool isDisabled, ) { return defaultItemBuilder( context, item[key], isSelected, isHighlighted, isDisabled, ); }; } @override _ListButtonState<T> createState() => _ListButtonState<T>(); } class _ListButtonState<T> extends State<ListButton<T>> { ListViewSelectionController? _selectionController; int _selectedIndex = -1; bool _pressed = false; _ConstraintsAdjuster _constraintsAdjuster = const _PassthroughAdjuster(); void _handleSelectionChanged() { setState(() { _selectedIndex = selectionController.selectedIndex; }); } void _updateButtonWidth() { switch (widget.width) { case ListButtonWidth.shrinkWrapCurrentItem: _constraintsAdjuster = const _PassthroughAdjuster(); break; case ListButtonWidth.shrinkWrapAllItems: const WidgetSurveyor surveyor = WidgetSurveyor(); final BasicListItemBuilder itemBuilder = _adaptBuilder( widget.builder, isForMeasurementOnly: true, ); double maxWidth = 0; for (int i = -1; i < widget.items.length; i++) { Widget built = _buildContent( itemBuilder, index: i, useLocalBuildContext: true, ); maxWidth = math.max(maxWidth, surveyor.measureWidget(built).width); } _constraintsAdjuster = _WidthTightener(maxWidth); break; case ListButtonWidth.expand: _constraintsAdjuster = _WidthMaximizer(); break; } } BasicListItemBuilder _adaptBuilder( ListButtonBuilder<T> builder, { bool isForMeasurementOnly = false, }) { return (BuildContext context, int index) { final T? item = index == -1 ? null : widget.items[index]; return builder(context, item, isForMeasurementOnly); }; } ListItemBuilder _adaptItemBuilder(ListButtonItemBuilder<T> itemBuilder) { return ( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { return itemBuilder( context, widget.items[index], isSelected, isHighlighted, isDisabled, ); }; } Predicate<int>? _adaptDisabledItemFilter(Predicate<T>? predicate) { if (predicate == null) { return null; } return (int index) { return predicate(widget.items[index]); }; } Widget _buildContent( BasicListItemBuilder itemBuilder, { int? index, bool useLocalBuildContext = false, }) { Widget result; if (useLocalBuildContext) { result = itemBuilder(context, index ?? _selectedIndex); } else { result = Builder( builder: (BuildContext context) { return itemBuilder(context, index ?? _selectedIndex); }, ); } return Padding( padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), child: result, ); } ListViewSelectionController get selectionController { return _selectionController ?? widget.selectionController!; } void showPopup() { final RenderBox button = context.findRenderObject() as RenderBox; final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox; final Offset buttonGlobalOffset = button.localToGlobal( Offset.zero, ancestor: overlay, ); // TODO: Why do we need to ceil here? final Offset buttonPosition = Offset( buttonGlobalOffset.dx.ceilToDouble(), buttonGlobalOffset.dy.ceilToDouble(), ); final _PopupListRoute<int> popupListRoute = _PopupListRoute<int>( position: RelativeRect.fromRect( buttonPosition & button.size, Offset.zero & overlay.size, ), length: widget.items.length, itemBuilder: _adaptItemBuilder(widget.itemBuilder), selectionController: selectionController, disabledItemFilter: _adaptDisabledItemFilter(widget.disabledItemFilter), showMenuContext: context, ); Navigator.of(context).push<int>(popupListRoute).then((int? selectedIndex) { if (mounted) { setState(() { _pressed = false; }); if (selectedIndex != null) { selectionController.selectedIndex = selectedIndex; } } }); } @override void initState() { super.initState(); if (widget.selectionController == null) { _selectionController = ListViewSelectionController(); } selectionController.addListener(_handleSelectionChanged); _handleSelectionChanged(); // to set the initial value of _selectedIndex } @override void didChangeDependencies() { super.didChangeDependencies(); _updateButtonWidth(); } @override void didUpdateWidget(covariant ListButton<T> oldWidget) { super.didUpdateWidget(oldWidget); _updateButtonWidth(); if (oldWidget.selectionController != widget.selectionController) { if (oldWidget.selectionController == null) { assert(_selectionController != null); _selectionController!.removeListener(_handleSelectionChanged); _selectionController!.dispose(); _selectionController = null; } else { assert(_selectionController == null); oldWidget.selectionController!.removeListener(_handleSelectionChanged); } if (widget.selectionController == null) { _selectionController = ListViewSelectionController(); _selectionController!.addListener(_handleSelectionChanged); } else { widget.selectionController!.addListener(_handleSelectionChanged); } _handleSelectionChanged(); // to set the initial value of _selectedIndex } } @override void dispose() { selectionController.removeListener(_handleSelectionChanged); if (_selectionController != null) { assert(widget.selectionController == null); _selectionController!.dispose(); _selectionController = null; } super.dispose(); } static const BoxDecoration _enabledDecoration = BoxDecoration( border: Border.fromBorderSide(BorderSide(color: Color(0xff999999))), gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: <Color>[Color(0xffdddcd5), Color(0xfff3f1fa)], ), ); static const BoxDecoration _pressedDecoration = BoxDecoration( border: Border.fromBorderSide(BorderSide(color: Color(0xff999999))), gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: <Color>[Color(0xffdddcd5), Color(0xffc8c7c0)], ), ); static const BoxDecoration _disabledDecoration = BoxDecoration( border: Border.fromBorderSide(BorderSide(color: Color(0xff999999))), color: const Color(0xffdddcd5), ); @override Widget build(BuildContext context) { final BasicListItemBuilder itemBuilder = _adaptBuilder(widget.builder); late final BoxDecoration decoration; if (widget.isEnabled) { decoration = _pressed ? _pressedDecoration : _enabledDecoration; } else { decoration = _disabledDecoration; } Widget result = DecoratedBox( decoration: decoration, child: Padding( padding: EdgeInsets.all(1), child: _RawListButton( childAdjuster: _constraintsAdjuster, roundToWholePixel: widget.roundToWholePixel, child: _buildContent(itemBuilder), ), ), ); if (widget.isEnabled) { result = MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTapDown: (TapDownDetails details) { setState(() { _pressed = true; }); }, onTapCancel: () { setState(() { _pressed = false; }); }, onTap: () { setState(() { showPopup(); }); }, child: result, ), ); } else { result = DefaultTextStyle( style: DefaultTextStyle.of( context, ).style.copyWith(color: const Color(0xff999999)), child: result, ); } return result; } } @immutable abstract class _ConstraintsAdjuster { const _ConstraintsAdjuster._(); BoxConstraints adjust(BoxConstraints constraints); } class _PassthroughAdjuster extends _ConstraintsAdjuster { const _PassthroughAdjuster() : super._(); @override BoxConstraints adjust(BoxConstraints constraints) => constraints; } class _WidthTightener extends _ConstraintsAdjuster { const _WidthTightener(this.width) : super._(); final double width; @override BoxConstraints adjust(BoxConstraints constraints) => constraints.tighten(width: width); } class _WidthMaximizer extends _ConstraintsAdjuster { const _WidthMaximizer() : super._(); @override BoxConstraints adjust(BoxConstraints constraints) => constraints.copyWith(minWidth: constraints.maxWidth); } class _RawListButton extends SingleChildRenderObjectWidget { const _RawListButton({ Key? key, required Widget child, required this.childAdjuster, this.roundToWholePixel = false, }) : super(key: key, child: child); final _ConstraintsAdjuster childAdjuster; final bool roundToWholePixel; @override Widget get child => super.child!; @override RenderObject createRenderObject(BuildContext context) { return _RenderRawListButton( childAdjuster: childAdjuster, roundToWholePixel: roundToWholePixel, ); } @override void updateRenderObject( BuildContext context, _RenderRawListButton renderObject, ) { renderObject ..childConstraintAdjuster = childAdjuster ..roundToWholePixel = roundToWholePixel; } } class _RenderRawListButton extends RenderBox with RenderObjectWithChildMixin<RenderBox>, RenderBoxWithChildDefaultsMixin { _RenderRawListButton({ required _ConstraintsAdjuster childAdjuster, bool roundToWholePixel = false, }) { this.childConstraintAdjuster = childAdjuster; this.roundToWholePixel = roundToWholePixel; } static const double _kMinHeight = 18; static const double _kPulldownWidth = 15; static const double _kDividerWidth = 1; static const double _kReservedWidth = _kPulldownWidth + _kDividerWidth; _ConstraintsAdjuster? _childConstraintAdjuster; _ConstraintsAdjuster get childConstraintAdjuster => _childConstraintAdjuster!; set childConstraintAdjuster(_ConstraintsAdjuster value) { if (_childConstraintAdjuster == value) return; _childConstraintAdjuster = value; markNeedsLayout(); } bool _roundToWholePixel = false; bool get roundToWholePixel => _roundToWholePixel; set roundToWholePixel(bool value) { if (_roundToWholePixel == value) return; _roundToWholePixel = value; markNeedsLayout(); } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { if (child != null) { final double? childBaseline = child!.getDistanceToActualBaseline( baseline, ); if (childBaseline != null) { final BoxParentData childParentData = child!.parentData as BoxParentData; return childBaseline + childParentData.offset.dy; } } return super.computeDistanceToActualBaseline(baseline); } @override double computeMinIntrinsicWidth(double height) { return (child == null ? 0 : child!.getMinIntrinsicWidth(height)) + _kReservedWidth; } @override double computeMaxIntrinsicWidth(double height) { return (child == null ? 0 : child!.getMinIntrinsicWidth(height)) + _kReservedWidth; } @override double computeMinIntrinsicHeight(double width) { return child == null ? _kMinHeight : math.max(child!.getMinIntrinsicHeight(width), _kMinHeight); } @override double computeMaxIntrinsicHeight(double width) { return child == null ? _kMinHeight : math.max(child!.getMinIntrinsicHeight(width), _kMinHeight); } double _dividerDx = 0; @override void performLayout() { Size childSize = Size.zero; if (child != null) { BoxConstraints childConstraints = constraints.deflate( EdgeInsets.only(left: _kReservedWidth), ); if (roundToWholePixel) { childConstraints = childConstraints.copyWith( maxWidth: childConstraints.maxWidth.floorToDouble(), ); } childConstraints = childConstraintAdjuster.adjust(childConstraints); assert(() { if (childConstraints.minWidth.isInfinite) { child!.layout(BoxConstraints.tight(Size.zero)); size = Size.zero; // To avoid ancillary exceptions that will confuse things. throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary( 'ListButtonWidth.expand cannot be used with unbounded with.', ), ErrorDescription( 'ListButtonWidth.expand causes a ListButton to expand to fill the ' 'available space. It cannot be used in a layout setting where it is given unbounded ' '(infinite) width constraints, because doing so would cause the ListButton to have ' 'infinite width, which is not allowed.', ), ErrorSpacer(), DiagnosticsProperty<BoxConstraints>( 'The constraints passed to the ListButton ' 'content were', constraints, ), ErrorSpacer(), DiagnosticsProperty<Object>( 'The widget tree that created the ListButton in question was', debugCreator, style: DiagnosticsTreeStyle.errorProperty, ), ]); } return true; }()); child!.layout(childConstraints, parentUsesSize: true); childSize = child!.size; if (roundToWholePixel) { childSize = Size(childSize.width.ceilToDouble(), childSize.height); } } size = constraints.constrainDimensions( childSize.width + _kReservedWidth, math.max(childSize.height, _kMinHeight), ); _dividerDx = childSize.width; if (child != null) { final BoxParentData childParentData = child!.parentData as BoxParentData; childParentData.offset = Offset(0, (size.height - childSize.height) / 2); } } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChild(result, position: position); } @override bool hitTestSelf(Offset position) => true; @override void paint(PaintingContext context, Offset offset) { defaultPaintChild(context, offset); Paint paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = const Color(0xff999999); context.canvas.drawLine( offset.translate(_dividerDx + 0.5, 0), offset.translate(_dividerDx + 0.5, size.height), paint, ); const _ArrowImage arrow = _ArrowImage(); final double pulldownWidth = size.width - (_dividerDx + 1); final double pulldownDx = (pulldownWidth - arrow.preferredSize.width) / 2; final double pulldownDy = (size.height - arrow.preferredSize.height) / 2; context.canvas ..save() ..translate( offset.dx + _dividerDx + 1 + pulldownDx, offset.dy + pulldownDy, ); try { arrow.paint(context.canvas, arrow.preferredSize); } finally { context.canvas.restore(); } } } class _PopupListRoute<T> extends PopupRoute<T> { _PopupListRoute({ required this.position, required this.length, required this.itemBuilder, required this.selectionController, this.disabledItemFilter, required this.showMenuContext, }); final RelativeRect position; final int length; final ListItemBuilder itemBuilder; final ListViewSelectionController selectionController; final Predicate<int>? disabledItemFilter; final BuildContext showMenuContext; @override Duration get transitionDuration => Duration.zero; @override Duration get reverseTransitionDuration => const Duration(milliseconds: 250); @override bool get barrierDismissible => true; @override Color? get barrierColor => null; @override String get barrierLabel => 'Dismiss'; @override Widget buildPage( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) { return SafeArea( child: CustomSingleChildLayout( delegate: _PopupListRouteLayout(position), child: InheritedTheme.captureAll( showMenuContext, _PopupList<T>( route: this, length: length, itemBuilder: itemBuilder, selectionController: selectionController, disabledItemFilter: disabledItemFilter, ), ), ), ); } } class _PopupListRouteLayout extends SingleChildLayoutDelegate { _PopupListRouteLayout(this.position); // Rectangle of underlying button, relative to the overlay's dimensions. final RelativeRect position; @override BoxConstraints getConstraintsForChild(BoxConstraints constraints) { const double padding = 8.0; return BoxConstraints.loose( constraints.biggest - const Offset(padding, padding) as Size, ); } /// `size` is the size of the overlay. /// /// `childSize` is the size of the menu, when fully open, as determined by /// [getConstraintsForChild]. @override Offset getPositionForChild(Size size, Size childSize) { final Rect buttonRect = position.toRect(Offset.zero & size); return Offset(buttonRect.left, buttonRect.bottom - 1); } @override bool shouldRelayout(_PopupListRouteLayout oldDelegate) => position != oldDelegate.position; } class _PopupList<T> extends StatefulWidget { const _PopupList({ required this.length, required this.itemBuilder, required this.selectionController, this.disabledItemFilter, required this.route, }); final int length; final ListItemBuilder itemBuilder; final ListViewSelectionController selectionController; final Predicate<int>? disabledItemFilter; final _PopupListRoute<T> route; @override _PopupListState<T> createState() => _PopupListState<T>(); } class _PopupListState<T> extends State<_PopupList<T>> { late ListViewSelectionController _selectionController; ListViewItemDisablerController? _itemDisabledController; late double _popupWidth; late double _itemHeight; void _handleSelectedIndexChanged() { Navigator.of(context).pop(_selectionController.selectedIndex); } void _updateListViewMetrics() { final TextDirection textDirection = Directionality.of(context); const WidgetSurveyor surveyor = WidgetSurveyor(); double maxWidth = 0; double maxHeight = 0; for (int i = 0; i < widget.length; i++) { final Widget item = Directionality( textDirection: textDirection, child: widget.itemBuilder(context, i, false, false, false), ); final Size itemSize = surveyor.measureWidget(item); maxWidth = math.max(maxWidth, itemSize.width); maxHeight = math.max(maxHeight, itemSize.height); } _popupWidth = maxWidth; _itemHeight = maxHeight; } ListViewItemDisablerController? _createItemDisabledController() { return widget.disabledItemFilter == null ? null : ListViewItemDisablerController(filter: widget.disabledItemFilter); } @override void initState() { super.initState(); _selectionController = ListViewSelectionController(); _selectionController.selectedIndex = widget.selectionController.selectedIndex; _selectionController.addListener(_handleSelectedIndexChanged); _itemDisabledController = _createItemDisabledController(); } @override void didChangeDependencies() { super.didChangeDependencies(); _updateListViewMetrics(); } @override void didUpdateWidget(covariant _PopupList<T> oldWidget) { super.didUpdateWidget(oldWidget); _updateListViewMetrics(); _itemDisabledController = _createItemDisabledController(); } @override void dispose() { _selectionController.removeListener(_handleSelectedIndexChanged); _selectionController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { const BoxShadow shadow = BoxShadow( color: Color(0x40000000), blurRadius: 3, offset: Offset(3, 3), ); final CurveTween opacity = CurveTween(curve: Curves.linear); return AnimatedBuilder( animation: widget.route.animation!, builder: (BuildContext context, Widget? child) { return Opacity( opacity: opacity.evaluate(widget.route.animation!), child: ClipRect( clipper: const _ShadowClipper(shadow), child: DecoratedBox( decoration: const BoxDecoration( color: Color(0xffffffff), border: Border.fromBorderSide( BorderSide(color: Color(0xff999999)), ), boxShadow: [shadow], ), child: Padding( padding: const EdgeInsets.all(1), child: SizedBox( width: _popupWidth, child: ScrollableListView( itemHeight: _itemHeight, length: widget.length, itemBuilder: widget.itemBuilder, selectionController: _selectionController, itemDisabledController: _itemDisabledController, ), ), ), ), ), ); }, ); } } class _ShadowClipper extends CustomClipper<Rect> { const _ShadowClipper(this.shadow); final BoxShadow shadow; @override Rect getClip(Size size) { final double shadowRadius = shadow.blurRadius * 2 + shadow.spreadRadius; return Offset.zero & (size + Offset(shadowRadius, shadowRadius)); } @override bool shouldReclip(_ShadowClipper oldClipper) => false; } class _ArrowImage { const _ArrowImage(); Size get preferredSize => const Size(7, 4); void paint(Canvas canvas, Size size) { Paint paint = Paint() ..style = PaintingStyle.fill ..isAntiAlias = true ..color = const Color(0xff000000); Path arrow = Path() ..fillType = PathFillType.evenOdd ..moveTo(0, 0) ..lineTo(size.width / 2, size.height + 0.5) ..lineTo(size.width, 0); arrow.close(); canvas.drawPath(arrow, paint); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/list_view.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart' hide ScrollController; import 'basic_list_view.dart'; import 'deferred_layout.dart'; import 'foundation.dart'; import 'listener_list.dart'; import 'scroll_pane.dart'; import 'span.dart'; void main() { runApp( Directionality( textDirection: TextDirection.ltr, child: DefaultTextStyle( style: TextStyle(fontFamily: 'Verdana', color: const Color(0xffffffff)), child: ScrollableListView( selectionController: ListViewSelectionController(), length: 1000, itemHeight: 20, itemBuilder: ( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { return Padding( padding: EdgeInsets.only(left: index.toDouble()), child: Text('$index'), ); }, ), ), ), ); } typedef ListItemBuilder = Widget Function( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ); class ListViewSelectionController with ChangeNotifier { ListViewSelectionController({this.selectMode = SelectMode.single}); final SelectMode selectMode; ListSelection _selectedRanges = ListSelection(); int get selectedIndex { assert(selectMode == SelectMode.single); return _selectedRanges.isEmpty ? -1 : _selectedRanges[0].start; } set selectedIndex(int index) { if (index == -1) { clearSelection(); } else { selectedRange = Span.single(index); } } Span? get selectedRange { assert(_selectedRanges.length <= 1); return _selectedRanges.isEmpty ? null : _selectedRanges[0]; } set selectedRange(Span? range) { if (range == null) { clearSelection(); } else { selectedRanges = <Span>[range]; } } Iterable<Span> get selectedRanges { return _selectedRanges.data; } set selectedRanges(Iterable<Span> ranges) { assert(selectMode != SelectMode.none, 'Selection is not enabled'); assert(() { if (selectMode == SelectMode.single) { if (ranges.length > 1) { return false; } if (ranges.isNotEmpty) { final Span range = ranges.single; if (range.length > 1) { return false; } } } return true; }()); final ListSelection selectedRanges = ListSelection(); for (Span range in ranges) { selectedRanges.addRange(range.start, range.end); } if (!const IterableEquality<Span>().equals( _selectedRanges.data, selectedRanges.data, )) { _selectedRanges = selectedRanges; notifyListeners(); } } int get firstSelectedIndex => _selectedRanges.isNotEmpty ? _selectedRanges.first.start : -1; int get lastSelectedIndex => _selectedRanges.isNotEmpty ? _selectedRanges.last.end : -1; Iterable<int> get selectedItems sync* { for (Span range in selectedRanges) { // ListSelection guarantees that `range` is already normalized. yield* Iterable<int>.generate( range.length, (int index) => range.start + index, ); } } set selectedItems(Iterable<int> indexes) { assert(selectMode != SelectMode.none, 'Selection is not enabled'); assert(indexes.length <= 1 || selectMode == SelectMode.multi); final ListSelection selectedRanges = ListSelection(); for (int index in indexes) { selectedRanges.addRange(index, index); } if (!const IterableEquality<Span>().equals( _selectedRanges.data, selectedRanges.data, )) { _selectedRanges = selectedRanges; notifyListeners(); } } bool addSelectedIndex(int index) { final List<Span> addedRanges = addSelectedRange(index, index); return addedRanges.isNotEmpty; } List<Span> addSelectedRange(int start, int end) { assert(selectMode == SelectMode.multi); final List<Span> addedRanges = _selectedRanges.addRange(start, end); if (addedRanges.isNotEmpty) { notifyListeners(); } return addedRanges; } bool removeSelectedIndex(int index) { List<Span> removedRanges = removeSelectedRange(index, index); return removedRanges.isNotEmpty; } List<Span> removeSelectedRange(int start, int end) { assert(selectMode == SelectMode.multi); final List<Span> removedRanges = _selectedRanges.removeRange(start, end); if (removedRanges.isNotEmpty) { notifyListeners(); } return removedRanges; } void clearSelection() { if (_selectedRanges.isNotEmpty) { _selectedRanges = ListSelection(); notifyListeners(); } } bool isItemSelected(int index) { return _selectedRanges.containsIndex(index); } } typedef ListViewItemDisabledFilterChangedHandler = void Function(Predicate<int>? previousFilter); class ListViewItemDisablerListener { const ListViewItemDisablerListener({ required this.onListViewItemDisabledFilterChanged, }); final ListViewItemDisabledFilterChangedHandler onListViewItemDisabledFilterChanged; } class ListViewItemDisablerController with ListenerNotifier<ListViewItemDisablerListener> { ListViewItemDisablerController({Predicate<int>? filter}) : _filter = filter; Predicate<int>? _filter; Predicate<int>? get filter => _filter; set filter(Predicate<int>? value) { Predicate<int>? previousValue = _filter; if (value != previousValue) { _filter = value; notifyListeners((ListViewItemDisablerListener listener) { listener.onListViewItemDisabledFilterChanged(previousValue); }); } } bool isItemDisabled(int index) => filter != null && filter!(index); } class ScrollableListView extends StatelessWidget { const ScrollableListView({ Key? key, required this.itemHeight, required this.length, required this.itemBuilder, this.selectionController, this.itemDisabledController, this.platform, this.scrollController, }) : super(key: key); final double itemHeight; final int length; final ListItemBuilder itemBuilder; final ListViewSelectionController? selectionController; final ListViewItemDisablerController? itemDisabledController; final TargetPlatform? platform; final ScrollPaneController? scrollController; @override Widget build(BuildContext context) { return ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.stretch, verticalScrollBarPolicy: ScrollBarPolicy.auto, controller: scrollController, view: ListView( itemHeight: itemHeight, length: length, itemBuilder: itemBuilder, selectionController: selectionController, itemDisabledController: itemDisabledController, platform: platform, ), ); } } class ListView extends RenderObjectWidget { const ListView({ Key? key, required this.itemHeight, required this.length, required this.itemBuilder, this.selectionController, this.itemDisabledController, this.platform, }) : super(key: key); final int length; final double itemHeight; final ListItemBuilder itemBuilder; final ListViewSelectionController? selectionController; final ListViewItemDisablerController? itemDisabledController; final TargetPlatform? platform; @override ListViewElement createElement() => ListViewElement(this); @override RenderListView createRenderObject(BuildContext context) { return RenderListView( itemHeight: itemHeight, length: length, selectionController: selectionController, itemDisabledController: itemDisabledController, platform: platform ?? defaultTargetPlatform, ); } @override void updateRenderObject(BuildContext context, RenderListView renderObject) { renderObject ..itemHeight = itemHeight ..length = length ..selectionController = selectionController ..itemDisabledController = itemDisabledController ..platform = platform ?? defaultTargetPlatform; } } class ListViewElement extends RenderObjectElement with ListViewElementMixin { ListViewElement(ListView listView) : super(listView); @override ListView get widget => super.widget as ListView; @override RenderListView get renderObject => super.renderObject as RenderListView; @override void update(ListView newWidget) { // We call `markNeedsBuild()` on the render object even if the itemBuilder // hasn't changed because the item builder might produce a different widget // even though the builder itself hasn't changed. renderObject.markNeedsBuild(); super.update(newWidget); } @override @protected Widget renderItem(int index) { return widget.itemBuilder( this, index, widget.selectionController?.isItemSelected(index) ?? false, renderObject.highlightedItem == index, widget.itemDisabledController?.isItemDisabled(index) ?? false, ); } } class RenderListView extends RenderBasicListView with DeferredLayoutMixin implements MouseTrackerAnnotation { RenderListView({ required double itemHeight, required int length, ListViewSelectionController? selectionController, ListViewItemDisablerController? itemDisabledController, required TargetPlatform platform, }) : super(itemHeight: itemHeight, length: length) { _itemDisablerListener = ListViewItemDisablerListener( onListViewItemDisabledFilterChanged: _handleItemDisabledFilterChanged, ); this.selectionController = selectionController; this.itemDisabledController = itemDisabledController; this.platform = platform; } late final ListViewItemDisablerListener _itemDisablerListener; late TapGestureRecognizer _tap; ListViewSelectionController? _selectionController; ListViewSelectionController? get selectionController => _selectionController; set selectionController(ListViewSelectionController? value) { if (_selectionController == value) return; if (attached && _selectionController != null) { _selectionController!.removeListener(_handleSelectionChanged); } _selectionController = value; if (attached && _selectionController != null) { _selectionController!.addListener(_handleSelectionChanged); } highlightedItem = null; markNeedsBuild(); } ListViewItemDisablerController? _itemDisabledController; ListViewItemDisablerController? get itemDisabledController => _itemDisabledController; set itemDisabledController(ListViewItemDisablerController? value) { if (_itemDisabledController == value) return; if (attached && _itemDisabledController != null) { _itemDisabledController!.removeListener(_itemDisablerListener); } _itemDisabledController = value; if (attached && _itemDisabledController != null) { _itemDisabledController!.addListener(_itemDisablerListener); } markNeedsBuild(); } bool _isItemDisabled(int index) => _itemDisabledController?.isItemDisabled(index) ?? false; TargetPlatform? _platform; TargetPlatform get platform => _platform!; set platform(TargetPlatform value) { if (value == _platform) return; _platform = value; } int? _highlightedItem; int? get highlightedItem => _highlightedItem; set highlightedItem(int? value) { if (_highlightedItem == value) return; final int? previousValue = _highlightedItem; _highlightedItem = value; final UnionListItemRange dirtyItems = UnionListItemRange(); if (previousValue != null) { dirtyItems.add(ListItemSequence(previousValue, previousValue)); } if (value != null) { dirtyItems.add(ListItemSequence(value, value)); } markItemsDirty(dirtyItems); } void _handleItemDisabledFilterChanged(Predicate<int>? previousFilter) { markNeedsBuild(); } void _handleSelectionChanged() { // TODO: be more precise about what to rebuild (requires finer grained info from the notification). markNeedsBuild(); } void _onPointerExit(PointerExitEvent event) { if (selectionController != null) { deferMarkNeedsLayout(() { highlightedItem = null; }); } } void _onPointerScroll(PointerScrollEvent event) { if (event.scrollDelta != Offset.zero) { deferMarkNeedsLayout(() { highlightedItem = null; }); } } void _onPointerHover(PointerHoverEvent event) { if (selectionController != null && event.kind == PointerDeviceKind.mouse) { deferMarkNeedsLayout(() { final int index = getItemAt(event.localPosition.dy); highlightedItem = index != -1 && !_isItemDisabled(index) ? index : null; }); } } _ListViewSelectionUpdateTask? _tapDownSelectionUpdateTask; void _handleTapDown(TapDownDetails details) { ListViewSelectionController? selectionController = this.selectionController; final SelectMode selectMode = selectionController?.selectMode ?? SelectMode.none; if (selectionController != null && selectMode != SelectMode.none) { final int index = getItemAt(details.localPosition.dy); if (index >= 0 && index < length && !_isItemDisabled(index)) { if (isShiftKeyPressed() && selectMode == SelectMode.multi) { final int startIndex = selectionController.firstSelectedIndex; if (startIndex == -1) { _tapDownSelectionUpdateTask = _ListViewAddToSelection(index); } else { final int endIndex = selectionController.lastSelectedIndex; final Span range = Span( index, index > startIndex ? startIndex : endIndex, ); _tapDownSelectionUpdateTask = _ListViewSetSelectedRange(range); } } else if (isPlatformCommandKeyPressed(platform) && selectMode == SelectMode.multi) { if (selectionController.isItemSelected(index)) { _tapDownSelectionUpdateTask = _ListViewRemoveFromSelection(index); } else { _tapDownSelectionUpdateTask = _ListViewAddToSelection(index); } } else if (isPlatformCommandKeyPressed(platform) && selectMode == SelectMode.single) { if (selectionController.isItemSelected(index)) { _tapDownSelectionUpdateTask = _ListViewSetSelectedIndex(-1); } else { _tapDownSelectionUpdateTask = _ListViewSetSelectedIndex(index); } } else if (selectMode != SelectMode.none) { _tapDownSelectionUpdateTask = _ListViewSetSelectedIndex(index); } } } } void _handleTapCancel() { _tapDownSelectionUpdateTask = null; } void _handleTap() { _tapDownSelectionUpdateTask?.run(selectionController); _tapDownSelectionUpdateTask = null; } @override MouseCursor get cursor => MouseCursor.defer; @override PointerEnterEventListener? get onEnter => null; @override PointerExitEventListener? get onExit => _onPointerExit; @override bool get validForMouseTracker => true; // Overridden to grant file-level visibility to this method. @override @protected void markNeedsBuild() { super.markNeedsBuild(); } @override void handleEvent(PointerEvent event, BoxHitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (event is PointerHoverEvent) return _onPointerHover(event); if (event is PointerScrollEvent) return _onPointerScroll(event); if (event is PointerDownEvent) return _tap.addPointer(event); super.handleEvent(event, entry); } @override void attach(PipelineOwner owner) { super.attach(owner); _tap = TapGestureRecognizer(debugOwner: this) ..onTapDown = _handleTapDown ..onTapCancel = _handleTapCancel ..onTap = _handleTap; if (_selectionController != null) { _selectionController!.addListener(_handleSelectionChanged); } if (_itemDisabledController != null) { _itemDisabledController!.addListener(_itemDisablerListener); } } @override void detach() { _tap.dispose(); if (_selectionController != null) { _selectionController!.removeListener(_handleSelectionChanged); } if (_itemDisabledController != null) { _itemDisabledController!.removeListener(_itemDisablerListener); } super.detach(); } @override void paint(PaintingContext context, Offset offset) { if (_highlightedItem != null) { final Rect rowBounds = getItemBounds(_highlightedItem!); final Paint paint = Paint() ..style = PaintingStyle.fill ..color = const Color(0xffdddcd5); context.canvas.drawRect(rowBounds.shift(offset), paint); } if (selectionController != null && selectionController!.selectedRanges.isNotEmpty) { final Paint paint = Paint() ..style = PaintingStyle.fill ..color = const Color(0xff14538b); for (Span range in selectionController!.selectedRanges) { Rect bounds = getItemBounds(range.start); bounds = bounds.expandToInclude(getItemBounds(range.end)); context.canvas.drawRect(bounds.shift(offset), paint); } } super.paint(context, offset); } } @immutable abstract class _ListViewSelectionUpdateTask { const _ListViewSelectionUpdateTask(); void run(ListViewSelectionController? controller); } class _ListViewAddToSelection extends _ListViewSelectionUpdateTask { const _ListViewAddToSelection(this.index); final int index; @override void run(ListViewSelectionController? controller) => controller?.addSelectedIndex(index); } class _ListViewRemoveFromSelection extends _ListViewSelectionUpdateTask { const _ListViewRemoveFromSelection(this.index); final int index; @override void run(ListViewSelectionController? controller) => controller?.removeSelectedIndex(index); } class _ListViewSetSelectedRange extends _ListViewSelectionUpdateTask { const _ListViewSetSelectedRange(this.range); final Span range; @override void run(ListViewSelectionController? controller) => controller?.selectedRange = range; } class _ListViewSetSelectedIndex extends _ListViewSelectionUpdateTask { const _ListViewSetSelectedIndex(this.index); final int index; @override void run(ListViewSelectionController? controller) => controller?.selectedIndex = index; }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/listener_list.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; import 'package:flutter/foundation.dart'; typedef ListenerVisitor<T> = void Function(T listener); final class _ListenerEntry<T extends Object> extends LinkedListEntry<_ListenerEntry<T>> { _ListenerEntry(this.listener); final T listener; } mixin ListenerNotifier<T extends Object> { LinkedList<_ListenerEntry<T>> _listeners = LinkedList<_ListenerEntry<T>>(); bool _debugDisposed = false; bool _debugAssertNotDisposed() { assert(() { if (_debugDisposed) { throw FlutterError( 'A $runtimeType was used after being disposed.\n' 'Once you have called dispose() on a $runtimeType, it can no longer be used.', ); } return true; }()); return true; } void addListener(T listener) { assert(_debugAssertNotDisposed()); _listeners.add(_ListenerEntry<T>(listener)); } void removeListener(T listener) { assert(_debugAssertNotDisposed()); for (final _ListenerEntry<T> entry in _listeners) { if (entry.listener == listener) { entry.unlink(); return; } } } @mustCallSuper void dispose() { assert(_debugAssertNotDisposed()); _listeners.clear(); _debugDisposed = true; } @protected void notifyListeners(ListenerVisitor<T> visitor) { assert(_debugAssertNotDisposed()); if (_listeners.isEmpty) return; final List<_ListenerEntry<T>> localListeners = List<_ListenerEntry<T>>.from( _listeners, ); for (final _ListenerEntry<T> entry in localListeners) { try { if (entry.list != null) { visitor(entry.listener); } } catch (exception, stack) { FlutterError.reportError( FlutterErrorDetails( exception: exception, stack: stack, library: 'chicago library', context: ErrorDescription( 'while dispatching notifications for $runtimeType', ), informationCollector: () sync* { yield DiagnosticsProperty<ListenerNotifier<T>>( 'The $runtimeType sending notification was', this, style: DiagnosticsTreeStyle.errorProperty, ); }, ), ); } } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/meter.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; class Meter extends SingleChildRenderObjectWidget { const Meter({ Key? key, required this.percentage, this.fillColor = const Color(0xff3c77b2), this.gridFrequency = 0.25, Widget? child, }) : super(key: key, child: child); Meter.simple({ Key? key, required this.percentage, this.fillColor = const Color(0xff3c77b2), this.gridFrequency = 0.25, String? text, }) : super(key: key, child: _textToChild(text)); final double percentage; final Color fillColor; final double gridFrequency; static Widget? _textToChild(String? text) { if (text == null) { return null; } return Text( text, style: const TextStyle( fontWeight: FontWeight.bold, color: Color(0xff000000), ), ); } @override RenderObject createRenderObject(BuildContext context) { return RenderMeter( percentage: percentage, fillColor: fillColor, gridFrequency: gridFrequency, ); } @override void updateRenderObject( BuildContext context, covariant RenderMeter renderObject, ) { renderObject ..percentage = percentage ..fillColor = fillColor ..gridFrequency = gridFrequency; } } class RenderMeter extends RenderBox with RenderObjectWithChildMixin<RenderBox> { RenderMeter({ required double percentage, required Color fillColor, required double gridFrequency, }) : _percentage = percentage, _fillColor = fillColor, _gridFrequency = gridFrequency; static const Size _defaultSize = Size(100, 12); static const double _borderWidth = 1; double _percentage; double get percentage => _percentage; set percentage(double value) { if (value != _percentage) { _percentage = value; markNeedsPaint(); } } Color _fillColor; Color get fillColor => _fillColor; set fillColor(Color value) { if (value != _fillColor) { _fillColor = value; markNeedsPaint(); } } double _gridFrequency; double get gridFrequency => _gridFrequency; set gridFrequency(double value) { if (value != _gridFrequency) { _gridFrequency = value; markNeedsPaint(); } } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { if (child != null) { final double? childBaseline = child!.getDistanceToActualBaseline( baseline, ); if (childBaseline != null) { final BoxParentData childParentData = child!.parentData as BoxParentData; return childBaseline + childParentData.offset.dy; } } return null; } @override double computeMinIntrinsicWidth(double height) { double result = _defaultSize.width; if (child != null) { final double childHeight = math.max(height - 2 * _borderWidth, 0); final double childWidth = child!.getMinIntrinsicWidth(childHeight); result = math.max(result, childWidth + 2 * _borderWidth); } return result; } @override double computeMaxIntrinsicWidth(double height) { double result = _defaultSize.width; if (child != null) { final double childHeight = math.max(height - 2 * _borderWidth, 0); final double childWidth = child!.getMaxIntrinsicWidth(childHeight); result = math.max(result, childWidth + 2 * _borderWidth); } return result; } @override double computeMinIntrinsicHeight(double width) { double result = _defaultSize.height; if (child != null) { final double childWidth = math.max(width - 2 * _borderWidth, 0); final double childHeight = child!.getMinIntrinsicHeight(childWidth); result = math.max(result, childHeight + 2 * _borderWidth); } return result; } @override double computeMaxIntrinsicHeight(double width) { double result = _defaultSize.height; if (child != null) { final double childWidth = math.max(width - 2 * _borderWidth, 0); final double childHeight = child!.getMaxIntrinsicHeight(childWidth); result = math.max(result, childHeight + 2 * _borderWidth); } return result; } @override Size computeDryLayout(BoxConstraints constraints) { Size dryLayoutSize = _defaultSize; if (child != null) { final BoxConstraints childConstraints = constraints.deflate( EdgeInsets.all(_borderWidth), ); final Size childSize = child!.getDryLayout(childConstraints); dryLayoutSize = Size( math.max(dryLayoutSize.width, childSize.width + 2 * _borderWidth), math.max(dryLayoutSize.height, childSize.height + 2 * _borderWidth), ); } return dryLayoutSize; } @override void performLayout() { Size preferredSize = _defaultSize; Size? childSize; if (child != null) { final BoxConstraints childConstraints = constraints.deflate( EdgeInsets.all(_borderWidth), ); child!.layout(childConstraints, parentUsesSize: true); childSize = child!.size; preferredSize = Size( math.max(preferredSize.width, childSize.width + 2 * _borderWidth), math.max(preferredSize.height, childSize.height + 2 * _borderWidth), ); } size = constraints.constrain(preferredSize); if (childSize != null) { final BoxParentData childParentData = child!.parentData as BoxParentData; childParentData.offset = Offset( (size.width - childSize.width) / 2, (size.height - childSize.height) / 2, ); } } @override void paint(PaintingContext context, Offset offset) { final Size innerSize = size - Offset(2 * _borderWidth, 2 * _borderWidth) as Size; final Offset innerOffset = offset.translate(_borderWidth, _borderWidth); // Draw the border. final Paint paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = _borderWidth ..color = const Color(0xffdddcd5); context.canvas.drawRect((offset & size).deflate(_borderWidth / 2), paint); // Draw the grid lines after the progress bar final double meterStopX = innerSize.width * percentage; _paintGridLines(context, offset, paint, startAt: meterStopX); // Save the layer so as to draw the progress bar on a transparent canvas, // thus allowing the BlendMode.xor to work as intended when we composite // the progress bar with the child. context.canvas.saveLayer( offset & size, Paint()..blendMode = BlendMode.srcOver, ); try { // Draw the progress bar. final Paint fillPaint = Paint() ..style = PaintingStyle.fill ..shader = ui.Gradient.linear( offset + Offset(0, 0), offset + Offset(0, size.height), <Color>[brighten(fillColor), darken(fillColor)], ); context.canvas.drawRect( innerOffset & Size(meterStopX, innerSize.height), fillPaint, ); // Paint the grid lines in the progress bar. _paintGridLines(context, offset, paint, stopAt: meterStopX); if (child != null) { context.canvas.saveLayer( offset & size, Paint()..blendMode = BlendMode.xor, ); try { final BoxParentData childParentData = child!.parentData as BoxParentData; context.paintChild(child!, offset + childParentData.offset); } finally { context.canvas.restore(); } } } finally { context.canvas.restore(); } } void _paintGridLines( PaintingContext context, Offset offset, Paint paint, { double startAt = 0, double stopAt = double.infinity, }) { assert(startAt < stopAt); final int nLines = (1 / gridFrequency).ceil() - 1; final double gridSeparation = size.width * gridFrequency; for (int i = 0; i < nLines; i++) { final double gridX = ((i + 1) * gridSeparation); if (gridX < startAt) { continue; } else if (gridX > stopAt) { break; } context.canvas.drawLine( offset + Offset(gridX, 0.5), offset + Offset(gridX, size.height - 0.5), paint, ); } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/navigator_listener.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/widgets.dart'; /// Signature for a function that receives [NavigatorObserver] notifications. /// /// See also: /// /// * [NavigatorListenerController.addObserver], where this signature is used. typedef NavigatorObserverCallback = void Function(Route<dynamic> route, Route<dynamic>? previousRoute); /// Signature for a function that receives [NavigatorObserver.didReplace] /// notifications. /// /// See also: /// /// * [NavigatorListenerController.addObserver], where this signature is used. typedef NavigatorObserverOnReplacedCallback = void Function(Route<dynamic>? route, Route<dynamic>? previousRoute); /// The result of a call to [NavigatorListenerController.addObserver]. /// /// This object represents a handle on the registration of a listener. Callers /// should call [dispose] to unregister their listener. class NavigatorListenerRegistration { const NavigatorListenerRegistration._(this._aggregateObserver, this._proxy); final _AggregateObserver _aggregateObserver; final _ProxyObserver _proxy; /// Causes the listener to stop receiving [NavigatorObserver] notifications. /// /// Failure to dispose of a registration can lead to memory leaks. void dispose() { _aggregateObserver.proxies.remove(_proxy); } } /// A widget that allows for dynamic registration of [NavigatorObserver] /// notifications. /// /// This widget should be placed above the [Navigator] in the widget hierarchy: /// /// ```dart /// void main() { /// runApp( /// NavigatorListener( /// child: MyApp(), /// ), /// ); /// } /// /// class MyApp extends StatelessWidget { /// @override /// Widget build(BuildContext context) { /// return MaterialApp( /// observers: [NavigatorListener.of(context).observer], /// home: MyHome(), /// ); /// } /// } /// ``` class NavigatorListener extends StatefulWidget { const NavigatorListener({Key? key, required this.child}) : super(key: key); /// The widget below this widget in the tree. /// /// This widget will match the size of its child. final Widget child; @override _NavigatorListenerState createState() => _NavigatorListenerState(); /// The controller from the closest instance of this class that encloses the /// given context. static NavigatorListenerController of(BuildContext context) { _Scope scope = context.dependOnInheritedWidgetOfExactType<_Scope>()!; return scope.navigatorListenerState; } } abstract class NavigatorListenerController { /// The underlying observer that will broadcast notifications to all /// child observers added via [addObserver]. /// /// This observer should be included in the [Navigator.observers] list when /// the navigator is created. This can be done by including a /// [NavigatorListener] widget as an ancestor of the [Navigator] widget, /// then specifying it like so: /// /// ```dart /// Navigator( /// observers: [ /// NavigatorListener.of(context).observer, /// ], /// ) /// ``` NavigatorObserver get observer; /// Adds a child observer to be notified of [NavigatorObserver] events. /// /// Callers should only specify the callbacks that they're interested in. /// /// The returned [NavigatorListenerRegistration] can be used to unregister /// the listener via [NavigatorListenerRegistration.dispose]. NavigatorListenerRegistration addObserver({ NavigatorObserverCallback? onPushed, NavigatorObserverCallback? onPopped, NavigatorObserverCallback? onRemoved, NavigatorObserverOnReplacedCallback? onReplaced, NavigatorObserverCallback? onStartUserGesture, VoidCallback? onStopUserGesture, }); } class _NavigatorListenerState extends State<NavigatorListener> implements NavigatorListenerController { @override final _AggregateObserver observer = _AggregateObserver(); @override NavigatorListenerRegistration addObserver({ NavigatorObserverCallback? onPushed, NavigatorObserverCallback? onPopped, NavigatorObserverCallback? onRemoved, NavigatorObserverOnReplacedCallback? onReplaced, NavigatorObserverCallback? onStartUserGesture, VoidCallback? onStopUserGesture, }) { final _ProxyObserver proxy = _ProxyObserver( onPushed: onPushed, onPopped: onPopped, onRemoved: onRemoved, onReplaced: onReplaced, onStartUserGesture: onStartUserGesture, onStopUserGesture: onStopUserGesture, ); observer.proxies.add(proxy); return NavigatorListenerRegistration._(observer, proxy); } @override Widget build(BuildContext context) { return _Scope(navigatorListenerState: this, child: widget.child); } } class _Scope extends InheritedWidget { const _Scope({required this.navigatorListenerState, required Widget child}) : super(child: child); final _NavigatorListenerState navigatorListenerState; @override bool updateShouldNotify(_Scope old) { return navigatorListenerState.observer != old.navigatorListenerState.observer; } } class _AggregateObserver extends NavigatorObserver { final Set<_ProxyObserver> proxies = <_ProxyObserver>{}; @override void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { for (NavigatorObserver proxy in proxies) { proxy.didPush(route, previousRoute); } } @override void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) { for (NavigatorObserver proxy in proxies) { proxy.didPop(route, previousRoute); } } @override void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) { for (NavigatorObserver proxy in proxies) { proxy.didRemove(route, previousRoute); } } @override void didReplace({Route<dynamic>? oldRoute, Route<dynamic>? newRoute}) { for (NavigatorObserver proxy in proxies) { proxy.didReplace(oldRoute: oldRoute, newRoute: newRoute); } } @override void didStartUserGesture( Route<dynamic> route, Route<dynamic>? previousRoute, ) { for (NavigatorObserver proxy in proxies) { proxy.didStartUserGesture(route, previousRoute); } } @override void didStopUserGesture() { for (NavigatorObserver proxy in proxies) { proxy.didStopUserGesture(); } } } class _ProxyObserver extends NavigatorObserver { _ProxyObserver({ this.onPushed, this.onPopped, this.onRemoved, this.onReplaced, this.onStartUserGesture, this.onStopUserGesture, }); final NavigatorObserverCallback? onPushed; final NavigatorObserverCallback? onPopped; final NavigatorObserverCallback? onRemoved; final NavigatorObserverOnReplacedCallback? onReplaced; final NavigatorObserverCallback? onStartUserGesture; final VoidCallback? onStopUserGesture; @override void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { if (onPushed != null) { onPushed!(route, previousRoute); } } @override void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) { if (onPopped != null) { onPopped!(route, previousRoute); } } @override void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) { if (onRemoved != null) { onRemoved!(route, previousRoute); } } @override void didReplace({Route<dynamic>? oldRoute, Route<dynamic>? newRoute}) { if (onReplaced != null) { onReplaced!(newRoute, oldRoute); } } @override void didStartUserGesture( Route<dynamic> route, Route<dynamic>? previousRoute, ) { if (onStartUserGesture != null) { onStartUserGesture!(route, previousRoute); } } @override void didStopUserGesture() { if (onStopUserGesture != null) { onStopUserGesture!(); } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/push_button.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart' show PopupMenuEntry, PopupMenuItemSelected, showMenu, Theme, Tooltip; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'action_tracker.dart'; import 'colors.dart'; import 'focus_indicator.dart'; import 'foundation.dart'; import 'sorting.dart'; const Axis _defaultAxis = Axis.horizontal; const Color _defaultColor = Color(0xff000000); const Color _defaultBackgroundColor = Color(0xffdddcd5); const Color _defaultBorderColor = Color(0xff999999); const Color _defaultDisabledBackgroundColor = Color(0xffdddcd5); const Color _defaultDisabledBorderColor = Color(0xff999999); const EdgeInsets _defaultPadding = EdgeInsets.symmetric( horizontal: 4, vertical: 4, ); const bool _defaultIsToolbar = false; const bool _defaultShowTooltip = true; const bool _defaultIsFocusable = true; class PushButton<T extends Object> extends StatefulWidget { const PushButton({ Key? key, this.icon, this.label, this.axis = _defaultAxis, this.isToolbar = _defaultIsToolbar, this.onPressed, this.menuItems, this.onMenuItemSelected, this.minimumAspectRatio, this.color = _defaultColor, this.backgroundColor = _defaultBackgroundColor, this.borderColor = _defaultBorderColor, this.disabledBackgroundColor = _defaultDisabledBackgroundColor, this.disabledBorderColor = _defaultDisabledBorderColor, this.padding = _defaultPadding, this.focusIndicatorPadding = const EdgeInsets.symmetric( horizontal: 2, vertical: 2, ), this.isFocusable = _defaultIsFocusable, this.autofocus = false, this.showTooltip = _defaultShowTooltip, }) : super(key: key); final String? icon; final String? label; final Axis axis; final bool isToolbar; final VoidCallback? onPressed; final List<PopupMenuEntry<T>>? menuItems; final PopupMenuItemSelected<T?>? onMenuItemSelected; final double? minimumAspectRatio; final Color color; final Color backgroundColor; final Color borderColor; final Color disabledBackgroundColor; final Color disabledBorderColor; final EdgeInsets padding; final EdgeInsets focusIndicatorPadding; final bool isFocusable; final bool autofocus; final bool showTooltip; @override _PushButtonState<T> createState() => _PushButtonState<T>(); } class _ActivatePushButtonAction<T extends Object> extends ActivateAction { _ActivatePushButtonAction(this._state); final _PushButtonState<T> _state; @override void invoke(Intent intent) { _state._handlePress(); } } class _PushButtonState<T extends Object> extends State<PushButton<T>> { bool hover = false; bool pressed = false; bool menuActive = false; bool focused = false; FocusNode? focusNode; void _handleFocusChange(bool hasFocus) { setState(() { focused = hasFocus; if (!hasFocus) { pressed = false; } }); } KeyEventResult _handleKey(FocusNode focusNode, KeyEvent event) { // The actual "pressing" of the button happens via the `ActivateIntent`. // This code merely visually shows the button in the pressed state. if (isActivateKey(event.logicalKey)) { setState(() { pressed = event is KeyDownEvent; }); } return KeyEventResult.ignored; } void _handlePress() { _handleSimplePress(); if (widget.menuItems != null) { _handleMenuPress(); } } void _handleSimplePress() { focusNode!.requestFocus(); if (widget.onPressed != null) { widget.onPressed!(); } } void _handleMenuPress() { setState(() { menuActive = true; }); final RenderBox button = context.findRenderObject() as RenderBox; final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox; final RelativeRect position = RelativeRect.fromRect( Rect.fromPoints( button.localToGlobal( button.size.bottomLeft(Offset.zero), ancestor: overlay, ), button.localToGlobal( button.size.bottomRight(Offset.zero), ancestor: overlay, ), ), Offset.zero & overlay.size, ); showMenu<T>( context: context, position: position, elevation: 4, items: widget.menuItems!, ).then((T? value) { if (mounted) { setState(() { menuActive = false; }); if (widget.onMenuItemSelected != null) { widget.onMenuItemSelected!(value); } } }); } LinearGradient get highlightGradient { return LinearGradient( begin: Alignment(0, 0.2), end: Alignment.topCenter, colors: <Color>[widget.backgroundColor, brighten(widget.backgroundColor)], ); } LinearGradient get pressedGradient { return LinearGradient( begin: Alignment.center, end: Alignment.topCenter, colors: <Color>[widget.backgroundColor, darken(widget.backgroundColor)], ); } bool get isEnabled => widget.onPressed != null; @override void initState() { super.initState(); focusNode = FocusNode(canRequestFocus: isEnabled); if (widget.autofocus) { focusNode!.requestFocus(); } } @override void didUpdateWidget(PushButton<T> oldWidget) { super.didUpdateWidget(oldWidget); if (widget.onPressed != oldWidget.onPressed) { focusNode!.canRequestFocus = isEnabled; if (!isEnabled) { hover = false; pressed = false; if (menuActive) { Navigator.of(context).pop(); menuActive = false; } } } } @override void dispose() { focusNode!.dispose(); focusNode = null; super.dispose(); } @override Widget build(BuildContext context) { final List<Widget> buttonData = <Widget>[]; if (widget.icon != null) { Widget iconImage = Image(image: AssetImage(widget.icon!)); if (!isEnabled) { iconImage = Opacity(opacity: 0.5, child: iconImage); } buttonData ..add(iconImage) ..add(SizedBox(width: 4, height: 4)); } if (widget.label != null) { TextStyle style = Theme.of(context).textTheme.bodyMedium!; if (isEnabled) { style = style.copyWith(color: widget.color); } else { style = style.copyWith(color: const Color(0xff999999)); } buttonData.add(Text(widget.label!, style: style)); } Widget button = widget.axis == Axis.horizontal ? Row(children: buttonData) : Column(children: buttonData); button = Center(child: Padding(padding: widget.padding, child: button)); if (!widget.isToolbar) { button = FocusIndicator( isFocused: focused, insets: widget.focusIndicatorPadding, color: widget.borderColor, child: button, ); } button = Actions( actions: <Type, Action<Intent>>{ ActivateIntent: _ActivatePushButtonAction<T>(this), }, child: Focus( canRequestFocus: isEnabled && widget.isFocusable, descendantsAreFocusable: isEnabled && widget.isFocusable, focusNode: focusNode, onKeyEvent: _handleKey, onFocusChange: _handleFocusChange, child: button, ), ); if (widget.menuItems != null) { button = Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Padding(padding: EdgeInsets.symmetric(horizontal: 4), child: button), Spacer(), Padding( padding: EdgeInsets.symmetric(horizontal: 4), child: CustomPaint( size: Size(7, 4), painter: SortIndicatorPainter( sortDirection: SortDirection.descending, color: const Color(0xff000000), ), ), ), ], ); } if (menuActive || hover || focused || !widget.isToolbar) { final Border border = Border.fromBorderSide( BorderSide( color: isEnabled ? widget.borderColor : widget.disabledBorderColor, ), ); Decoration decoration; if (isEnabled && (pressed || menuActive)) { decoration = BoxDecoration(border: border, gradient: pressedGradient); } else if (isEnabled) { decoration = BoxDecoration(border: border, gradient: highlightGradient); } else { decoration = BoxDecoration( border: border, color: widget.disabledBackgroundColor, ); } button = DecoratedBox(decoration: decoration, child: button); } if (isEnabled) { if (widget.showTooltip && widget.label != null) { button = Tooltip( message: widget.label!, waitDuration: Duration(seconds: 1, milliseconds: 500), child: button, ); } button = MouseRegion( cursor: SystemMouseCursors.click, onEnter: (PointerEnterEvent event) { setState(() => hover = true); }, onExit: (PointerExitEvent event) { setState(() => hover = false); }, child: Listener( onPointerDown: (PointerDownEvent event) { setState(() => pressed = true); }, onPointerUp: (PointerUpEvent event) { setState(() => pressed = false); }, child: GestureDetector(onTap: _handlePress, child: button), ), ); } if (widget.minimumAspectRatio != null) { button = _MinimumAspectRatio(minimumAspectRatio: 3, child: button); } return button; } } class _MinimumAspectRatio extends SingleChildRenderObjectWidget { const _MinimumAspectRatio({ Key? key, required Widget child, required this.minimumAspectRatio, }) : super(key: key, child: child); final double minimumAspectRatio; @override _RenderMinimumAspectRatio createRenderObject(BuildContext context) { return _RenderMinimumAspectRatio(minimumAspectRatio: minimumAspectRatio); } @override void updateRenderObject( BuildContext context, _RenderMinimumAspectRatio renderObject, ) { renderObject..minimumAspectRatio = minimumAspectRatio; } } class _RenderMinimumAspectRatio extends RenderProxyBox { _RenderMinimumAspectRatio({ RenderBox? child, required double minimumAspectRatio, }) : super(child) { this.minimumAspectRatio = minimumAspectRatio; } double? _minimumAspectRatio; double get minimumAspectRatio => _minimumAspectRatio!; set minimumAspectRatio(double value) { if (value == _minimumAspectRatio) return; _minimumAspectRatio = value; markNeedsLayout(); } @override double computeMinIntrinsicWidth(double height) { if (child == null) { return 0.0; } if (!height.isFinite) { height = child!.getMaxIntrinsicHeight(double.infinity); } assert(height.isFinite); return math.max( height * minimumAspectRatio, child!.getMinIntrinsicWidth(height), ); } @override double computeMaxIntrinsicWidth(double height) { if (child == null) { return 0.0; } if (!height.isFinite) { height = child!.getMaxIntrinsicHeight(double.infinity); } assert(height.isFinite); return math.max( height * minimumAspectRatio, child!.getMaxIntrinsicWidth(height), ); } @override double computeMinIntrinsicHeight(double width) { return computeMaxIntrinsicHeight(width); } @override void performLayout() { if (child != null) { BoxConstraints childConstraints = constraints; if (!childConstraints.hasTightHeight) { final double height = child!.getMaxIntrinsicHeight( childConstraints.maxWidth, ); assert(height.isFinite); childConstraints = childConstraints.tighten(height: height); } childConstraints = childConstraints.copyWith( minWidth: childConstraints.constrainWidth( childConstraints.maxHeight * minimumAspectRatio, ), ); child!.layout(childConstraints, parentUsesSize: true); size = child!.size; } else { performResize(); } } } class CommandPushButton extends StatelessWidget { const CommandPushButton({ Key? key, required this.label, this.autofocus = false, required this.onPressed, }) : super(key: key); final String label; final bool autofocus; final VoidCallback? onPressed; @override Widget build(BuildContext context) { return PushButton( color: const Color(0xffffffff), backgroundColor: const Color(0xff3c77b2), borderColor: const Color(0xff2b5580), padding: EdgeInsets.fromLTRB(3, 4, 4, 5), autofocus: autofocus, showTooltip: false, minimumAspectRatio: 3, onPressed: onPressed, label: label, ); } } class ActionPushButton<I extends Intent> extends ActionTracker<I> { const ActionPushButton({ Key? key, required I intent, ValueChanged<Object?>? onActionInvoked, this.icon, this.label, this.axis = _defaultAxis, this.isToolbar = _defaultIsToolbar, this.minimumAspectRatio, this.color = _defaultColor, this.backgroundColor = _defaultBackgroundColor, this.borderColor = _defaultBorderColor, this.padding = _defaultPadding, this.showTooltip = _defaultShowTooltip, this.isFocusable = _defaultIsFocusable, }) : super(key: key, intent: intent, onActionInvoked: onActionInvoked); final String? icon; final String? label; final Axis axis; final bool isToolbar; final double? minimumAspectRatio; final Color color; final Color backgroundColor; final Color borderColor; final EdgeInsets padding; final bool showTooltip; final bool isFocusable; @override _ActionPushButtonState<I> createState() => _ActionPushButtonState<I>(); } class _ActionPushButtonState<I extends Intent> extends State<ActionPushButton<I>> with ActionTrackerStateMixin<I, ActionPushButton<I>> { @override Widget build(BuildContext context) { return PushButton( icon: widget.icon, label: widget.label, axis: widget.axis, isToolbar: widget.isToolbar, onPressed: isEnabled ? invokeAction : null, minimumAspectRatio: widget.minimumAspectRatio, color: widget.color, backgroundColor: widget.backgroundColor, borderColor: widget.borderColor, padding: widget.padding, showTooltip: widget.showTooltip, isFocusable: widget.isFocusable, ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/radio_button.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:ui' as ui; import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'focus_indicator.dart'; class RadioButtonController<T> extends ValueNotifier<T?> { RadioButtonController([T? value]) : super(value); } class RadioButton<T> extends StatefulWidget { const RadioButton({ Key? key, required this.value, required this.controller, this.spacing = 4, this.trailing, this.isEnabled = true, this.onSelected, this.semanticLabel, }) : super(key: key); final T value; final RadioButtonController<T> controller; final double spacing; final Widget? trailing; final bool isEnabled; final VoidCallback? onSelected; final String? semanticLabel; @override _RadioButtonState<T> createState() => _RadioButtonState<T>(); } class _RadioButtonState<T> extends State<RadioButton<T>> { FocusNode? _focusNode; bool _isFocused = false; void _handleFocusChange(bool hasFocus) { setState(() { _isFocused = hasFocus; }); } void _handleTap() { _focusNode!.requestFocus(); } void _handleGroupValueChanged() { setState(() { // State is held in our controller. }); } void _handleSelected() { _handleTap(); widget.controller.value = widget.value; if (widget.onSelected != null) { widget.onSelected!(); } } @override void initState() { super.initState(); _focusNode = FocusNode(canRequestFocus: widget.isEnabled); widget.controller.addListener(_handleGroupValueChanged); } @override void didUpdateWidget(covariant RadioButton<T> oldWidget) { super.didUpdateWidget(oldWidget); _focusNode!.canRequestFocus = widget.isEnabled; } @override void dispose() { widget.controller.removeListener(_handleGroupValueChanged); _focusNode!.dispose(); _focusNode = null; super.dispose(); } @override Widget build(BuildContext context) { final bool isSelected = widget.value == widget.controller.value; final VoidCallback? onSelected = widget.isEnabled ? _handleSelected : null; return Semantics( excludeSemantics: true, label: widget.semanticLabel ?? 'Radio button', inMutuallyExclusiveGroup: true, enabled: widget.isEnabled, button: true, focusable: widget.isEnabled, focused: _isFocused, toggled: isSelected, onTap: onSelected, child: Actions( actions: <Type, Action<Intent>>{ ActivateIntent: _ActivateRadioButtonAction<T>(this), }, child: Focus( focusNode: _focusNode, onFocusChange: _handleFocusChange, child: FocusIndicator( isFocused: _isFocused, child: GestureDetector( onTap: _handleTap, child: BasicRadioButton( key: widget.key, isSelected: isSelected, spacing: widget.spacing, trailing: widget.trailing, onSelected: onSelected, ), ), ), ), ), ); } } class _ActivateRadioButtonAction<T> extends ActivateAction { _ActivateRadioButtonAction(this._state); final _RadioButtonState<T> _state; @override void invoke(Intent intent) { _state._handleSelected(); } } class BasicRadioButton extends StatelessWidget { const BasicRadioButton({ Key? key, this.isSelected = false, this.spacing = 4, this.trailing, this.onSelected, }) : super(key: key); final bool isSelected; final double spacing; final Widget? trailing; final VoidCallback? onSelected; @override Widget build(BuildContext context) { final bool isEnabled = onSelected != null; Widget? styledTrailing = trailing; if (styledTrailing != null) { styledTrailing = Padding( padding: EdgeInsets.only(left: spacing), child: styledTrailing, ); if (!isEnabled) { styledTrailing = Opacity(opacity: 0.5, child: styledTrailing); } } Widget result = Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ _RawRadioButton(isSelected: isSelected, isEnabled: isEnabled), if (styledTrailing != null) styledTrailing, ], ); if (isEnabled) { result = MouseRegion( cursor: SystemMouseCursors.click, child: AbsorbPointer(child: result), ); if (!isSelected) { result = GestureDetector(onTap: onSelected, child: result); } } return result; } } class _RawRadioButton extends LeafRenderObjectWidget { const _RawRadioButton({ Key? key, required this.isSelected, required this.isEnabled, }) : super(key: key); final bool isSelected; final bool isEnabled; @override RenderObject createRenderObject(BuildContext context) { return _RenderRawRadioButton(isSelected: isSelected, isEnabled: isEnabled); } @override void updateRenderObject( BuildContext context, covariant _RenderRawRadioButton renderObject, ) { renderObject ..isSelected = isSelected ..isEnabled = isEnabled; } } class _RenderRawRadioButton extends RenderBox { _RenderRawRadioButton({bool isSelected = false, bool isEnabled = true}) : _isSelected = isSelected, _isEnabled = isEnabled; static const double _diameter = 14; static const double _selectionDiameter = 6; late bool _isSelected; bool get isSelected => _isSelected; set isSelected(bool value) { if (value != _isSelected) { _isSelected = value; markNeedsPaint(); } } late bool _isEnabled; bool get isEnabled => _isEnabled; set isEnabled(bool value) { if (value != _isEnabled) { _isEnabled = value; markNeedsPaint(); } } @override void performLayout() { size = constraints.constrainDimensions(_diameter, _diameter); } @override void paint(PaintingContext context, Offset offset) { final Color buttonColor = const Color(0xffffffff); final Color borderColor; final Color selectionColor; final Paint paint = Paint(); final Rect backgroundCircle = Rect.fromLTWH( 1, 1, _diameter - 3, _diameter - 3, ); if (isEnabled) { paint.shader = ui.Gradient.radial( backgroundCircle.center, backgroundCircle.width * 2 / 3, <Color>[darken(buttonColor), buttonColor], ); borderColor = const Color(0xff999999); selectionColor = const Color(0xff2b5580); } else { paint.color = const Color(0xffe6e6e6); borderColor = const Color(0xff999999); selectionColor = const Color(0xff999999); } // Center the button vertically context.canvas.save(); context.canvas.translate( offset.dx, offset.dy + (size.height - _diameter) / 2, ); try { // Paint the border final Paint borderPaint = Paint()..color = borderColor; context.canvas.drawOval( Rect.fromLTWH(0, 0, _diameter - 1, _diameter - 1), borderPaint, ); // Paint the background context.canvas.drawOval(backgroundCircle, paint); // Paint the selection if (isSelected) { Paint selectionPaint = Paint()..color = selectionColor; final Rect selection = Rect.fromLTWH( (_diameter - _selectionDiameter) / 2, (_diameter - _selectionDiameter) / 2, _selectionDiameter - 1, _selectionDiameter - 1, ); context.canvas.drawOval(selection, selectionPaint); } } finally { context.canvas.restore(); } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/rollup.dart
Dart
import 'dart:math' as math; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'focus_indicator.dart'; const double _arrowWidth = 7; class RollupController extends ChangeNotifier { RollupController({bool isExpanded = false}) : _isExpanded = isExpanded; bool _isExpanded; bool get isExpanded => _isExpanded; set isExpanded(bool value) { if (value != _isExpanded) { _isExpanded = value; notifyListeners(); } } void toggleExpanded() { isExpanded = !isExpanded; } } class Rollup extends StatefulWidget { const Rollup({ Key? key, required this.heading, required this.childBuilder, this.controller, this.isCollapsible = true, this.semanticLabel, }) : super(key: key); final Widget heading; final WidgetBuilder childBuilder; final RollupController? controller; final bool isCollapsible; final String? semanticLabel; @override _RollupState createState() => _RollupState(); } class _RollupState extends State<Rollup> { RollupController? _controller; FocusNode? _focusNode; RollupController get controller => _controller ?? widget.controller!; void _handleToggleExpanded() { controller.toggleExpanded(); } void _handleIsExpandedChanged() { setState(() { // We pull our expanded state from the controller. }); } @override void initState() { super.initState(); if (widget.controller == null) { _controller = RollupController(); } controller.addListener(_handleIsExpandedChanged); _focusNode = FocusNode(); } @override void didUpdateWidget(covariant Rollup oldWidget) { super.didUpdateWidget(oldWidget); if (widget.controller != oldWidget.controller) { final RollupController oldController = _controller ?? oldWidget.controller!; oldController.removeListener(_handleIsExpandedChanged); _controller?.dispose(); _controller = null; if (widget.controller == null) { _controller = RollupController(); } controller.addListener(_handleIsExpandedChanged); } } @override void dispose() { controller.removeListener(_handleIsExpandedChanged); _controller?.dispose(); _controller = null; _focusNode!.dispose(); _focusNode = null; super.dispose(); } @override Widget build(BuildContext context) { return RawRollup( heading: widget.heading, childBuilder: widget.childBuilder, focusNode: _focusNode!, isExpanded: controller.isExpanded, isCollapsible: widget.isCollapsible, onToggleExpanded: _handleToggleExpanded, semanticLabel: widget.semanticLabel, ); } } class RawRollup extends ImplicitlyAnimatedWidget { const RawRollup({ Key? key, required this.heading, required this.childBuilder, required this.focusNode, required this.isExpanded, required this.isCollapsible, required this.onToggleExpanded, required this.semanticLabel, }) : super( key: key, duration: const Duration(milliseconds: 250), curve: Curves.easeOut, ); final Widget heading; final WidgetBuilder childBuilder; final FocusNode focusNode; final bool isExpanded; final bool isCollapsible; final VoidCallback onToggleExpanded; final String? semanticLabel; @override _RawRollupState createState() => _RawRollupState(); } class _RawRollupState extends AnimatedWidgetBaseState<RawRollup> { bool _isFocused = false; Tween<double>? _expansionTween; Tween<double>? _arrowRotationTween; void _handleFocusChange(bool hasFocus) { setState(() { _isFocused = hasFocus; }); } @override void forEachTween(TweenVisitor<dynamic> visitor) { _expansionTween = visitor( _expansionTween, widget.isExpanded ? 1.0 : 0.0, (dynamic value) => Tween<double>(begin: value as double), ) as Tween<double>?; _arrowRotationTween = visitor( _arrowRotationTween, widget.isExpanded ? math.pi / 2 : 0.0, (dynamic value) => Tween<double>(begin: value as double), ) as Tween<double>?; } @override Widget build(BuildContext context) { final double reveal = _expansionTween?.evaluate(animation) ?? 1; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: widget.onToggleExpanded, child: Actions( actions: <Type, Action<Intent>>{ ActivateIntent: _ActivateRollupAction(this), }, child: Semantics( label: widget.semanticLabel ?? 'Rollup widget', focusable: true, focused: _isFocused, child: Focus( focusNode: widget.focusNode, onFocusChange: _handleFocusChange, child: FocusIndicator( isFocused: _isFocused, insets: EdgeInsets.fromLTRB(-3, 0, -3, -1), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Transform.rotate( angle: _arrowRotationTween?.evaluate(animation) ?? 0.0, child: CustomPaint( size: Size.square(_arrowWidth), painter: _ArrowPainter(), ), ), SizedBox(width: 4), widget.heading, ], ), ), ), ), ), ), ), if (reveal > 0) _RevealBox( reveal: reveal, child: Padding( padding: EdgeInsets.only(top: 4), child: Row( mainAxisSize: MainAxisSize.min, children: [ SizedBox(width: _arrowWidth), SizedBox(width: 4), widget.childBuilder(context), ], ), ), ), ], ); } } class _ActivateRollupAction extends ActivateAction { _ActivateRollupAction(this._state); final _RawRollupState _state; @override void invoke(Intent intent) { _state.widget.onToggleExpanded(); } } class _RevealBox extends SingleChildRenderObjectWidget { const _RevealBox({Key? key, required this.reveal, required Widget? child}) : super(key: key, child: child); final double reveal; @override RenderObject createRenderObject(BuildContext context) { return _RenderRevealBox(reveal: reveal); } @override void updateRenderObject( BuildContext context, covariant _RenderRevealBox renderObject, ) { renderObject..reveal = reveal; } } class _RenderRevealBox extends RenderProxyBox { _RenderRevealBox({required double reveal}) : _reveal = reveal; double? _reveal; double get reveal => _reveal!; set reveal(double value) { if (value != _reveal) { _reveal = value; markNeedsLayout(); } } @override void performLayout() { super.performLayout(); final Size childSize = child!.size; size = Size(childSize.width, childSize.height * reveal); } @override bool get alwaysNeedsCompositing => true; @override void paint(PaintingContext context, Offset offset) { _clipRectLayer.layer = context.pushClipRect( needsCompositing, offset, Offset.zero & size, super.paint, clipBehavior: Clip.hardEdge, oldLayer: _clipRectLayer.layer, ); } @override void dispose() { _clipRectLayer.layer = null; super.dispose(); } final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>(); } class _ArrowPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = const Color(0xffc4c3bc) ..style = PaintingStyle.fill; final Path path = Path() ..lineTo(7, 3.5) ..lineTo(0, 7) ..close(); canvas.drawPath(path, paint); } @override bool shouldRepaint(covariant _ArrowPainter oldDelegate) => false; }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/scroll_bar.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart' as colorUtils; import 'listener_list.dart'; class ScrollBar extends StatelessWidget { const ScrollBar({ Key? key, this.orientation = Axis.vertical, this.unitIncrement = 1, this.blockIncrement = 1, }) : super(key: key); /// This scroll bar's orientation. /// /// This defaults to [Axis.vertical] if it's not specified in the /// constructor. /// /// changing a scroll bar's orientation when rebuilding the widget is /// currently not supported. final Axis orientation; /// The value adjustment that will be made (up or down) when the user presses /// the scroll bar buttons. final double unitIncrement; /// The value adjustment that will be made (up or down) when the user taps /// on the scroll bar track (on either side of the scroll bar handle). final double blockIncrement; @override Widget build(BuildContext context) { return _ScrollBar( orientation: orientation, unitIncrement: unitIncrement, blockIncrement: blockIncrement, upButton: _ScrollBarButton(orientation: orientation, direction: -1), downButton: _ScrollBarButton(orientation: orientation, direction: 1), handle: _ScrollBarHandle(orientation: orientation), track: _ScrollBarTrack(orientation: orientation), ); } } class _ScrollBarButton extends LeafRenderObjectWidget { const _ScrollBarButton({ Key? key, required this.orientation, required this.direction, }) : super(key: key); final Axis orientation; final int direction; @override RenderObject createRenderObject(BuildContext context) { return _RenderScrollBarButton( orientation: orientation, direction: direction, ); } @override void updateRenderObject( BuildContext context, _RenderScrollBarButton renderObject, ) { assert(orientation == renderObject.orientation); } } class _ScrollBarHandle extends LeafRenderObjectWidget { const _ScrollBarHandle({Key? key, required this.orientation}) : super(key: key); final Axis orientation; @override RenderObject createRenderObject(BuildContext context) { return _RenderScrollBarHandle(orientation: orientation); } @override void updateRenderObject( BuildContext context, _RenderScrollBarHandle renderObject, ) { assert(orientation == renderObject.orientation); } } class _ScrollBarTrack extends LeafRenderObjectWidget { const _ScrollBarTrack({Key? key, required this.orientation}) : super(key: key); final Axis orientation; @override RenderObject createRenderObject(BuildContext context) { return _RenderScrollBarTrack(orientation: orientation); } @override void updateRenderObject( BuildContext context, _RenderScrollBarTrack renderObject, ) { assert(orientation == renderObject.orientation); } } class _ScrollBar extends RenderObjectWidget { const _ScrollBar({ Key? key, required this.orientation, required this.unitIncrement, required this.blockIncrement, required this.upButton, required this.downButton, required this.handle, required this.track, }) : super(key: key); final Axis orientation; final double unitIncrement; final double blockIncrement; final Widget upButton; final Widget downButton; final Widget handle; final Widget track; @override RenderObjectElement createElement() => _ScrollBarElement(this); @override RenderObject createRenderObject(BuildContext context) { return RenderScrollBar( orientation: orientation, unitIncrement: unitIncrement, blockIncrement: blockIncrement, ); } @override void updateRenderObject(BuildContext context, RenderScrollBar renderObject) { renderObject ..orientation = orientation ..unitIncrement = unitIncrement ..blockIncrement = blockIncrement; } } enum _ScrollBarSlot { upButton, downButton, handle, track } class _ScrollBarElement extends RenderObjectElement { _ScrollBarElement(_ScrollBar widget) : super(widget); Element? _upButton; Element? _downButton; Element? _handle; Element? _track; @override _ScrollBar get widget => super.widget as _ScrollBar; @override RenderScrollBar get renderObject => super.renderObject as RenderScrollBar; @override void update(_ScrollBar newWidget) { super.update(newWidget); assert(widget == newWidget); _updateChildren(newWidget); } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _updateChildren(widget); } void _updateChildren(_ScrollBar widget) { _upButton = updateChild( _upButton, widget.upButton, _ScrollBarSlot.upButton, ); _downButton = updateChild( _downButton, widget.downButton, _ScrollBarSlot.downButton, ); _handle = updateChild(_handle, widget.handle, _ScrollBarSlot.handle); _track = updateChild(_track, widget.track, _ScrollBarSlot.track); } @override void visitChildren(ElementVisitor visitor) { if (_upButton != null) visitor(_upButton!); if (_downButton != null) visitor(_downButton!); if (_handle != null) visitor(_handle!); if (_track != null) visitor(_track!); } @override void insertRenderObjectChild(RenderBox child, _ScrollBarSlot slot) { _updateChildSlot(slot, child); } @override void moveRenderObjectChild( RenderObject child, dynamic oldSlot, dynamic newSlot, ) { assert(false); } @override void removeRenderObjectChild(RenderBox child, _ScrollBarSlot slot) { assert(child.parent == renderObject); _updateChildSlot(slot, null); } void _updateChildSlot(_ScrollBarSlot slot, RenderBox? child) { switch (slot) { case _ScrollBarSlot.upButton: renderObject.upButton = child as _RenderScrollBarButton?; break; case _ScrollBarSlot.downButton: renderObject.downButton = child as _RenderScrollBarButton?; break; case _ScrollBarSlot.handle: renderObject.handle = child as _RenderScrollBarHandle?; break; case _ScrollBarSlot.track: renderObject.track = child as _RenderScrollBarTrack?; break; } } } class ScrollBarConstraints extends BoxConstraints { const ScrollBarConstraints({ double minWidth = 0, double maxWidth = double.infinity, double minHeight = 0, double maxHeight = double.infinity, this.enabled = true, required this.start, required this.end, required this.value, required this.extent, }) : super( minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight, ); ScrollBarConstraints.fromBoxConstraints({ required BoxConstraints boxConstraints, this.enabled = true, required this.start, required this.end, required this.value, required this.extent, }) : super( minWidth: boxConstraints.minWidth, maxWidth: boxConstraints.maxWidth, minHeight: boxConstraints.minHeight, maxHeight: boxConstraints.maxHeight, ); final bool enabled; final double start; final double end; final double value; final double extent; @override bool get isNormalized { return super.isNormalized && start < end && value >= start && value + extent <= end; } @override ScrollBarConstraints normalize() { if (isNormalized) { return this; } final double end = start < this.end ? this.end : start + 1; final double value = this.value >= start && this.value < end ? this.value : start; return ScrollBarConstraints.fromBoxConstraints( boxConstraints: super.normalize(), start: start, end: end, value: value, extent: extent <= end - value ? extent : end - value, ); } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is ScrollBarConstraints && super == other && other.enabled == enabled && other.start == start && other.end == end && other.value == value && other.extent == extent; } @override int get hashCode { assert(debugAssertIsValid()); return Object.hash(super.hashCode, enabled, start, end, value, extent); } @override String toString() { return 'ScrollBarConstraints(base=${super.toString()}, enabled=$enabled, start=$start, 3nd=$end, value=$value, extent=$extent)'; } } class RenderScrollBar extends RenderBox with ListenerNotifier<ScrollBarValueListener> { RenderScrollBar({ Axis orientation = Axis.vertical, double unitIncrement = 1, double blockIncrement = 1, bool enabled = true, double start = 0, double end = 100, double extent = 1, double value = 0, }) : _orientation = orientation, _unitIncrement = unitIncrement, _blockIncrement = blockIncrement, _enabled = enabled, _start = start, _end = end, _extent = extent, _value = value { automaticScroller = _AutomaticScroller(scrollBar: this); } late final _AutomaticScroller automaticScroller; late Size _upButtonSize; late Size _downButtonSize; late Size _handleSize; static const double _minimumHandleLength = 31; Axis _orientation; Axis get orientation => _orientation; set orientation(Axis value) { if (_orientation == value) return; _orientation = value; markNeedsLayout(); } _RenderScrollBarButton? _upButton; _RenderScrollBarButton? get upButton => _upButton; set upButton(_RenderScrollBarButton? value) { if (value == _upButton) return; if (_upButton != null) dropChild(_upButton!); _upButton = value; if (_upButton != null) adoptChild(_upButton!); } _RenderScrollBarButton? _downButton; _RenderScrollBarButton? get downButton => _downButton; set downButton(_RenderScrollBarButton? value) { if (value == _downButton) return; if (_downButton != null) dropChild(_downButton!); _downButton = value; if (_downButton != null) adoptChild(_downButton!); } _RenderScrollBarHandle? _handle; _RenderScrollBarHandle? get handle => _handle; set handle(_RenderScrollBarHandle? value) { if (value == _handle) return; if (_handle != null) dropChild(_handle!); _handle = value; if (_handle != null) adoptChild(_handle!); } _RenderScrollBarTrack? _track; _RenderScrollBarTrack? get track => _track; set track(_RenderScrollBarTrack? value) { if (value == _track) return; if (_track != null) dropChild(_track!); _track = value; if (_track != null) adoptChild(_track!); } bool _enabled; bool get enabled => _enabled; double _start; double get start => _start; double _end; double get end => _end; double _extent; double get extent => _extent; double _value; double get value => _value; set value(double value) { if (!_updateValue(value)) return; // markNeedsLayout() would yield the correct behavior but would do more // work than needed. If all that has changed is the value, we can just // update the handle's location and save the work of a full layout. if (handle!.parentData!.visible) { if (orientation == Axis.horizontal) { final double handleX = (value * _pixelValueRatio) + _upButtonSize.width - 1; handle!.parentData!.offset = Offset(handleX, 1); } else { final double handleY = (value * _pixelValueRatio) + _upButtonSize.height - 1; handle!.parentData!.offset = Offset(1, handleY); } } markNeedsPaint(); } /// Updates the value of [RenderScrollBar.value]. /// /// If and only if the value was updated, this will notify listeners. /// /// Returns true if the value was updated, or false if the value didn't change. bool _updateValue(double value) { if (_value == value) return false; double previousValue = _value; _value = value; notifyListeners((ScrollBarValueListener listener) { listener.valueChanged(this, previousValue); }); return true; } double _unitIncrement; double get unitIncrement => _unitIncrement; set unitIncrement(double value) { if (_unitIncrement == value) return; _unitIncrement = value; } double _blockIncrement; double get blockIncrement => _blockIncrement; set blockIncrement(double value) { if (_blockIncrement == value) return; _blockIncrement = value; } /// The ratio of logical pixel to scroll bar value. /// /// For example, if every time the scroll bar moves one pixel, its value /// moves by two, then this ratio would be 2.0. double get _pixelValueRatio { double maxLegalRealValue = end - extent; double numLegalRealValues = maxLegalRealValue - start + 1; double numLegalPixelValues; // Track pixel values add two to account for the handle border overlapping // the button borders by 1 pixel to form a shared border. if (orientation == Axis.horizontal) { double trackWidth = size.width - _upButtonSize.width - _downButtonSize.width + 2; numLegalPixelValues = trackWidth - _handleSize.width + 1; } else { double trackHeight = size.height - _upButtonSize.height - _downButtonSize.height + 2; numLegalPixelValues = trackHeight - _handleSize.height + 1; } return numLegalPixelValues / numLegalRealValues; } @override ScrollBarConstraints get constraints => super.constraints as ScrollBarConstraints; _AutomaticScrollerParameters? _getTrackScrollParameters(Offset position) { if (!handle!.parentData!.visible) { return null; } // Calculate the direction of the scroll by checking to see if the user // pressed the pointer in the area "before" the handle or "after" it. final int direction; final double realStopValue; if (orientation == Axis.horizontal) { direction = position.dx < handle!.parentData!.offset.dx ? -1 : 1; double pixelStopValue = position.dx - _upButtonSize.width + 1; if (direction == 1) { // If we're scrolling down, account for the width of the // handle in our pixel stop value so that we stop as soon // as the *bottom* of the handle reaches our click point pixelStopValue -= _handleSize.width; } realStopValue = pixelStopValue / _pixelValueRatio; } else { direction = position.dy < handle!.parentData!.offset.dy ? -1 : 1; double pixelStopValue = position.dy - _upButtonSize.height + 1; if (direction == 1) { // If we're scrolling down, account for the height of the // handle in our pixel stop value so that we stop as soon // as the *bottom* of the handle reaches our click point pixelStopValue -= _handleSize.height; } realStopValue = pixelStopValue / _pixelValueRatio; } return _AutomaticScrollerParameters(direction, realStopValue); } @override void setupParentData(RenderBox child) { if (child.parentData is! _ScrollBarParentData) child.parentData = _ScrollBarParentData(); } @override void attach(PipelineOwner owner) { super.attach(owner); upButton?.attach(owner); downButton?.attach(owner); handle?.attach(owner); track?.attach(owner); } @override void detach() { super.detach(); upButton?.detach(); downButton?.detach(); handle?.detach(); track?.detach(); } @override void visitChildren(RenderObjectVisitor visitor) { if (upButton != null) visitor(upButton!); if (downButton != null) visitor(downButton!); if (handle != null) visitor(handle!); if (track != null) visitor(track!); } @override double computeMinIntrinsicHeight(double width) { if (orientation == Axis.horizontal) { return math.max( upButton!.getMinIntrinsicHeight(width), downButton!.getMinIntrinsicHeight(width), ); } else { return upButton!.getMinIntrinsicHeight(width) + downButton!.getMinIntrinsicHeight(width); } } @override double computeMinIntrinsicWidth(double height) { if (orientation == Axis.horizontal) { return upButton!.getMinIntrinsicWidth(height) + downButton!.getMinIntrinsicWidth(height); } else { return math.max( upButton!.getMinIntrinsicWidth(height), downButton!.getMinIntrinsicWidth(height), ); } } @override void performLayout() { assert(constraints.isTight); size = constraints.smallest; _enabled = constraints.enabled; upButton!.enabled = constraints.enabled; downButton!.enabled = constraints.enabled; _start = constraints.start; _end = constraints.end; _updateValue(constraints.value); // notifies listeners _extent = constraints.extent; double maxLegalRealValue = end - extent; double numLegalRealValues = maxLegalRealValue - start + 1; double extentPercentage = extent / (end - start); track!.layout(constraints); track!.parentData!.visible = true; if (orientation == Axis.horizontal) { upButton!.layout( BoxConstraints.tightFor(height: size.height), parentUsesSize: true, ); upButton!.parentData!.visible = true; upButton!.parentData!.offset = Offset.zero; downButton!.layout( BoxConstraints.tightFor(height: size.height), parentUsesSize: true, ); downButton!.parentData!.visible = true; downButton!.parentData!.offset = Offset( size.width - downButton!.size.width, 0, ); if (size.width < upButton!.size.width + downButton!.size.width) { upButton!.parentData!.visible = false; downButton!.parentData!.visible = false; } if (enabled) { // Calculate the handle width first, as it dictates how much // room is left to represent the range of legal values. Note // that the handle may overlap each scroll button by 1px so // that its borders merge into the borders of the scroll buttons double availableWidth = size.width - upButton!.size.width - downButton!.size.width + 2; double handleWidth = math.max( _minimumHandleLength, (extentPercentage * availableWidth), ); // Calculate the position of the handle by calculating the // scale that maps logical value to pixel value double numLegalPixelValues = availableWidth - handleWidth + 1; double valueScale = numLegalPixelValues / numLegalRealValues; double handleX = (value * valueScale) + upButton!.size.width - 1; if (handleWidth > availableWidth) { // If we can't fit the handle, we hide it handle!.layout(BoxConstraints.tight(Size.zero), parentUsesSize: true); handle!.parentData!.visible = false; } else { handle!.layout( BoxConstraints.tightFor( width: handleWidth, height: size.height - 2, ), parentUsesSize: true, ); handle!.parentData!.visible = true; handle!.parentData!.offset = Offset(handleX, 1); } } else { handle!.layout(BoxConstraints.tight(Size.zero), parentUsesSize: true); handle!.parentData!.visible = false; } } else { upButton!.layout( BoxConstraints.tightFor(width: size.width), parentUsesSize: true, ); upButton!.parentData!.visible = true; upButton!.parentData!.offset = Offset.zero; downButton!.layout( BoxConstraints.tightFor(width: size.width), parentUsesSize: true, ); downButton!.parentData!.visible = true; downButton!.parentData!.offset = Offset( 0, size.height - downButton!.size.height, ); if (size.height < upButton!.size.height + downButton!.size.height) { upButton!.parentData!.visible = false; downButton!.parentData!.visible = false; } if (enabled) { // Calculate the handle height first, as it dictates how much // room is left to represent the range of legal values. Note // that the handle may overlap each scroll button by 1px so // that its borders merge into the borders of the scroll buttons double availableHeight = size.height - upButton!.size.height - downButton!.size.height + 2; double handleHeight = math.max( _minimumHandleLength, (extentPercentage * availableHeight), ); // Calculate the position of the handle by calculating the // scale maps logical value to pixel value double numLegalPixelValues = availableHeight - handleHeight + 1; double valueScale = numLegalPixelValues / numLegalRealValues; double handleY = (value * valueScale) + upButton!.size.height - 1; if (handleHeight > availableHeight) { // If we can't fit the handle, we hide it handle!.layout(BoxConstraints.tight(Size.zero), parentUsesSize: true); handle!.parentData!.visible = false; } else { handle!.layout( BoxConstraints.tightFor( width: size.width - 2, height: handleHeight, ), parentUsesSize: true, ); handle!.parentData!.visible = true; handle!.parentData!.offset = Offset(1, handleY); } } else { handle!.layout(BoxConstraints.tight(Size.zero), parentUsesSize: true); handle!.parentData!.visible = false; } } _upButtonSize = upButton!.size; _downButtonSize = downButton!.size; _handleSize = handle!.size; } @override void paint(PaintingContext context, Offset offset) { for (RenderBox child in <RenderBox>[ track!, upButton!, downButton!, handle!, ]) { final _ScrollBarParentData childParentData = child.parentData as _ScrollBarParentData; if (childParentData.visible) { context.paintChild(child, childParentData.offset + offset); } } } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { for (RenderBox child in <RenderBox>[ upButton!, downButton!, handle!, track!, ]) { final _ScrollBarParentData childParentData = child.parentData as _ScrollBarParentData; final bool isHit = result.addWithPaintOffset( offset: childParentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - childParentData.offset); return child.hitTest(result, position: transformed); }, ); if (isHit) { return true; } } return false; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty<Axis>('orientation', orientation)); properties.add(DiagnosticsProperty<bool>('enabled', enabled)); properties.add(DoubleProperty('start', start)); properties.add(DoubleProperty('end', end)); properties.add(DoubleProperty('extent', extent)); properties.add(DoubleProperty('value', value)); properties.add(DoubleProperty('unitIncrement', unitIncrement)); properties.add(DoubleProperty('blockIncrement', blockIncrement)); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> result = <DiagnosticsNode>[]; void add(RenderBox? child, String name) { if (child != null) result.add(child.toDiagnosticsNode(name: name)); } add(upButton, 'upButton'); add(downButton, 'downButton'); add(handle, 'handle'); add(track, 'track'); return result; } } class _ScrollBarParentData extends ContainerBoxParentData<RenderBox> { /// Whether the child should be painted. bool visible = false; @override String toString() => '${super.toString()}; visible=$visible'; } typedef ScrollBarValueChangedHandler = void Function(RenderScrollBar scrollBar, double previousValue); class ScrollBarValueListener { const ScrollBarValueListener({required this.valueChanged}); /// Called when a scroll bar's value has changed. final ScrollBarValueChangedHandler valueChanged; } class _RenderScrollBarButton extends RenderBox implements MouseTrackerAnnotation { _RenderScrollBarButton({ this.orientation = Axis.vertical, this.direction = 1, }); final Axis orientation; final int direction; late final LongPressGestureRecognizer _longPress; static const double _length = 15; bool _enabled = true; bool get enabled => _enabled; set enabled(bool value) { if (_enabled == value) return; parent!.automaticScroller.stop(); _enabled = value; markNeedsPaint(); } bool _highlighted = false; bool get highlighted => _highlighted; set highlighted(bool value) { if (_highlighted == value) return; _highlighted = value; markNeedsPaint(); } bool _pressed = false; bool get pressed => _pressed; set pressed(bool value) { if (_pressed == value) return; _pressed = value; markNeedsPaint(); } void _onEnter(PointerEnterEvent event) { highlighted = true; } void _onExit(PointerExitEvent event) { parent!.automaticScroller.stop(); highlighted = false; pressed = false; } void _handleLongPressDown(LongPressDownDetails details) { parent!.automaticScroller.scroll(direction, _ScrollType.unit); pressed = true; } void _handleLongPressCancel() { parent!.automaticScroller.stop(); pressed = false; } void _handleLongPressStart(LongPressStartDetails details) { parent!.automaticScroller.start(direction, _ScrollType.unit); } void _handleLongPressEnd(LongPressEndDetails details) { parent!.automaticScroller.stop(); pressed = false; } @override RenderScrollBar? get parent => super.parent as RenderScrollBar?; @override _ScrollBarParentData? get parentData => super.parentData as _ScrollBarParentData?; @override MouseCursor get cursor => MouseCursor.defer; @override PointerEnterEventListener? get onEnter => _onEnter; @override PointerExitEventListener? get onExit => _onExit; @override bool get validForMouseTracker => true; @override void attach(PipelineOwner owner) { super.attach(owner); _longPress = LongPressGestureRecognizer( debugOwner: this, duration: _AutomaticScroller._delay, ) ..onLongPressDown = _handleLongPressDown ..onLongPressCancel = _handleLongPressCancel ..onLongPressStart = _handleLongPressStart ..onLongPressEnd = _handleLongPressEnd; } @override void detach() { _longPress.dispose(); super.detach(); } @override void handleEvent(PointerEvent event, BoxHitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (!enabled) return; if (event is PointerDownEvent) return _longPress.addPointer(event); } @override bool hitTestSelf(ui.Offset position) => true; @override double computeMinIntrinsicHeight(double width) => _length; @override double computeMinIntrinsicWidth(double height) => _length; @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) { return constraints.constrain(Size.square(_length)); } @override void paint(PaintingContext context, Offset offset) { _ScrollButtonPainter painter = _ScrollButtonPainter( enabled: enabled, pressed: pressed, highlighted: highlighted, orientation: orientation, arrow: _ArrowImage(orientation: orientation, direction: direction), ); context.canvas.save(); try { context.canvas.translate(offset.dx, offset.dy); painter.paint(context.canvas, size); } finally { context.canvas.restore(); } } } class _RenderScrollBarHandle extends RenderBox implements MouseTrackerAnnotation { _RenderScrollBarHandle({required this.orientation}); final Axis orientation; late final PanGestureRecognizer _pan; bool _highlighted = false; bool get highlighted => _highlighted; set highlighted(bool value) { if (_highlighted == value) return; _highlighted = value; markNeedsPaint(); } void _onEnter(PointerEnterEvent event) { highlighted = true; } void _onExit(PointerExitEvent event) { highlighted = false; } double? _dragOffset; void _handlePanDown(DragDownDetails details) { _dragOffset = orientation == Axis.horizontal ? details.localPosition.dx - parentData!.offset.dx + parent!._upButtonSize.width - 1 : details.localPosition.dy - parentData!.offset.dy + parent!._upButtonSize.height - 1; } void _handlePanCancel() { _resetPan(); } void _handlePanUpdate(DragUpdateDetails details) { if (_dragOffset != null) { // Calculate the new scroll bar value double pixelValue; if (orientation == Axis.horizontal) { pixelValue = details.localPosition.dx - _dragOffset!; } else { pixelValue = details.localPosition.dy - _dragOffset!; } double scrollBarValue = (pixelValue / parent!._pixelValueRatio); scrollBarValue = math.min( math.max(scrollBarValue, 0), parent!.end - parent!.extent, ); parent!.value = scrollBarValue; } } void _handlePanEnd(DragEndDetails details) { _resetPan(); } void _resetPan() { _dragOffset = null; markNeedsPaint(); } @override RenderScrollBar? get parent => super.parent as RenderScrollBar?; @override _ScrollBarParentData? get parentData => super.parentData as _ScrollBarParentData?; @override MouseCursor get cursor => MouseCursor.defer; @override PointerEnterEventListener? get onEnter => _onEnter; @override PointerExitEventListener? get onExit => _onExit; @override bool get validForMouseTracker => true; @override void attach(PipelineOwner owner) { super.attach(owner); _pan = PanGestureRecognizer(debugOwner: this) ..onDown = _handlePanDown ..onCancel = _handlePanCancel ..onUpdate = _handlePanUpdate ..onEnd = _handlePanEnd; } @override void detach() { _pan.dispose(); super.detach(); } @override void handleEvent(PointerEvent event, BoxHitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (event is PointerDownEvent) return _pan.addPointer(event); } @override bool hitTestSelf(ui.Offset position) => true; @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) => constraints.smallest; @override void paint(PaintingContext context, Offset offset) { _HandlePainter painter = _HandlePainter( highlighted: highlighted || _dragOffset != null, orientation: orientation, ); context.canvas.save(); try { context.canvas.translate( offset.dx.floorToDouble(), offset.dy.floorToDouble(), ); painter.paint(context.canvas, size); } finally { context.canvas.restore(); } } } class _RenderScrollBarTrack extends RenderBox implements MouseTrackerAnnotation { _RenderScrollBarTrack({required this.orientation}); final Axis orientation; late final LongPressGestureRecognizer _longPress; _AutomaticScrollerParameters? _scroll; void _handleLongPressDown(LongPressDownDetails details) { _scroll = parent._getTrackScrollParameters( details.localPosition + parentData!.offset, ); if (_scroll != null) { parent.automaticScroller.scroll(_scroll!.direction, _ScrollType.block); } } void _handleLongPressCancel() { parent.automaticScroller.stop(); _scroll = null; } void _handleLongPressStart(LongPressStartDetails details) { if (_scroll != null) { parent.automaticScroller.start( _scroll!.direction, _ScrollType.block, _scroll!.stopValue, ); } } void _handleLongPressEnd(LongPressEndDetails details) { parent.automaticScroller.stop(); _scroll = null; } void _handleExit(PointerExitEvent event) { parent.automaticScroller.stop(); } @override RenderScrollBar get parent => super.parent as RenderScrollBar; @override _ScrollBarParentData? get parentData => super.parentData as _ScrollBarParentData?; @override MouseCursor get cursor => MouseCursor.defer; @override PointerEnterEventListener? get onEnter => null; @override PointerExitEventListener? get onExit => _handleExit; @override bool get validForMouseTracker => true; @override void attach(PipelineOwner owner) { super.attach(owner); _longPress = LongPressGestureRecognizer( debugOwner: this, duration: _AutomaticScroller._delay, ) ..onLongPressDown = _handleLongPressDown ..onLongPressCancel = _handleLongPressCancel ..onLongPressStart = _handleLongPressStart ..onLongPressEnd = _handleLongPressEnd; } @override void detach() { _longPress.dispose(); super.detach(); } @override void handleEvent(PointerEvent event, covariant BoxHitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (event is PointerDownEvent) return _longPress.addPointer(event); } @override bool hitTestSelf(ui.Offset position) => true; @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) => constraints.smallest; @override void paint(PaintingContext context, Offset offset) { final Paint bgPaint = Paint()..style = PaintingStyle.fill; final Paint borderPaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = const Color(0xff999999); const List<Color> colors = <Color>[Color(0xffc5c3bc), Color(0xffdedcd4)]; switch (orientation) { case Axis.horizontal: bgPaint.shader = ui.Gradient.linear( offset + Offset(0, 1.5), offset + Offset(0, size.height - 1.5), colors, ); context.canvas.drawRect(offset & size, bgPaint); context.canvas.drawLine( offset + Offset(0, 0.5), offset + Offset(size.width, 0.5), borderPaint, ); context.canvas.drawLine( offset + Offset(0, size.height - 0.5), offset + Offset(size.width, size.height - 0.5), borderPaint, ); break; case Axis.vertical: bgPaint.shader = ui.Gradient.linear( offset + Offset(1.5, 0), offset + Offset(size.width - 1.5, 0), colors, ); context.canvas.drawRect(offset & size, bgPaint); context.canvas.drawLine( offset + Offset(0.5, 0), offset + Offset(0.5, size.height), borderPaint, ); context.canvas.drawLine( offset + Offset(size.width - 0.5, 0), offset + Offset(size.width - 0.5, size.height), borderPaint, ); break; } } } enum _ScrollType { unit, block } class _ScrollButtonPainter extends CustomPainter { const _ScrollButtonPainter({ required this.enabled, required this.pressed, required this.highlighted, required this.orientation, required this.arrow, }); final bool enabled; final bool pressed; final bool highlighted; final Axis orientation; final _ArrowImage arrow; @override void paint(Canvas canvas, Size size) { Color backgroundColor; if (enabled) { if (pressed) { backgroundColor = const Color(0xffc5c3bc); } else if (highlighted) { backgroundColor = const Color(0xfff7f5ee); } else { backgroundColor = const Color(0xffdddcd5); } } else { backgroundColor = const Color(0xffcccccc); } Color brightBackgroundColor = colorUtils.brighten(backgroundColor); // Paint the background Color gradientStartColor = pressed ? backgroundColor : brightBackgroundColor; Color gradientEndColor = pressed ? brightBackgroundColor : backgroundColor; List<Color> colors = <Color>[gradientStartColor, gradientEndColor]; Paint bgPaint = Paint()..style = PaintingStyle.fill; if (orientation == Axis.horizontal) { if (enabled) bgPaint.shader = ui.Gradient.linear( Offset(0, 1.5), Offset(0, size.height - 1.5), colors, ); else bgPaint.color = backgroundColor; } else { if (enabled) bgPaint.shader = ui.Gradient.linear( Offset(1.5, 0), Offset(size.width - 1.5, 0), colors, ); else bgPaint.color = backgroundColor; } canvas.drawRect( Offset(1, 1) & Size(size.width - 2, size.height - 2), bgPaint, ); // Paint the border Paint borderPaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = const Color(0xff999999); canvas.drawRect((Offset.zero & size).deflate(0.5), borderPaint); // Paint the arrow double arrowX = (size.width - arrow.preferredSize.width) / 2; double arrowY = (size.height - arrow.preferredSize.height) / 2; canvas.save(); try { canvas.translate(arrowX, arrowY); arrow.paint(canvas, arrow.preferredSize); } finally { canvas.restore(); } } @override bool shouldRepaint(CustomPainter oldDelegate) { // TODO: implement shouldRepaint return true; } } abstract class _ArrowImage { const _ArrowImage._(this.orientation); factory _ArrowImage({required Axis orientation, required int direction}) { if (direction > 0) { return _UpArrowImage(orientation); } else { return _DownArrowImage(orientation); } } final Axis orientation; Size get preferredSize => orientation == Axis.horizontal ? Size(5, 7) : Size(7, 5); void paint(Canvas canvas, Size size); } class _UpArrowImage extends _ArrowImage { const _UpArrowImage(Axis orientation) : super._(orientation); @override void paint(Canvas canvas, Size size) { Paint arrowPaint = Paint() ..style = PaintingStyle.fill ..color = const Color(0xff000000); Path arrow = Path()..fillType = PathFillType.evenOdd; switch (orientation) { case Axis.horizontal: arrow ..moveTo(0, 0) ..lineTo(size.width + 0.5, size.height / 2) ..lineTo(0, size.height); break; case Axis.vertical: arrow ..moveTo(0, 0) ..lineTo(size.width / 2, size.height + 0.5) ..lineTo(size.width, 0); break; } arrow.close(); canvas.drawPath(arrow, arrowPaint); } } class _DownArrowImage extends _ArrowImage { const _DownArrowImage(Axis orientation) : super._(orientation); @override void paint(Canvas canvas, Size size) { Paint arrowPaint = Paint() ..style = PaintingStyle.fill ..color = const Color(0xff000000); Path arrow = Path()..fillType = PathFillType.evenOdd; switch (orientation) { case Axis.horizontal: arrow ..moveTo(size.width, 0) ..lineTo(-0.5, size.height / 2) ..lineTo(size.width, size.height); break; case Axis.vertical: arrow ..moveTo(0, size.height) ..lineTo(size.width / 2, -0.5) ..lineTo(size.width, size.height); break; } arrow.close(); canvas.drawPath(arrow, arrowPaint); } } class _HandlePainter extends CustomPainter { const _HandlePainter({required this.highlighted, required this.orientation}); final bool highlighted; final Axis orientation; @override void paint(Canvas canvas, Size size) { Color backgroundColor = highlighted ? const Color(0xfff7f5ee) : const Color(0xffdbdad3); Color brightBackgroundColor = colorUtils.brighten(backgroundColor); Color darkBackgroundColor = colorUtils.darken(backgroundColor); List<Color> colors = <Color>[brightBackgroundColor, backgroundColor]; Paint paint = Paint()..style = PaintingStyle.fill; if (orientation == Axis.horizontal) { paint.shader = ui.Gradient.linear( Offset(0, 0.5), Offset(0, size.height - 0.5), colors, ); } else { paint.shader = ui.Gradient.linear( Offset(0.5, 0), Offset(size.width - 0.5, 0), colors, ); } canvas.drawRect(Offset.zero & size, paint); // Paint the border Paint borderPaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1 ..color = const Color(0xff999999); if (orientation == Axis.horizontal) { canvas.drawLine(Offset(0.5, 0), Offset(0.5, size.height), borderPaint); canvas.drawLine( Offset(size.width - 0.5, 0), Offset(size.width - 0.5, size.height), borderPaint, ); } else { canvas.drawLine(Offset(0, 0.5), Offset(size.width, 0.5), borderPaint); canvas.drawLine( Offset(0, size.height - 0.5), Offset(size.width, size.height - 0.5), borderPaint, ); } // Paint the hash marks Paint hashPaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1; if (orientation == Axis.horizontal) { final double mid = size.width / 2; hashPaint.color = darkBackgroundColor; canvas.drawLine( Offset(mid - 3.5, 2.5), Offset(mid - 3.5, size.height - 2.5), hashPaint, ); canvas.drawLine( Offset(mid - 0.5, 2.5), Offset(mid - 0.5, size.height - 2.5), hashPaint, ); canvas.drawLine( Offset(mid + 2.5, 2.5), Offset(mid + 2.5, size.height - 2.5), hashPaint, ); hashPaint.color = brightBackgroundColor; canvas.drawLine( Offset(mid - 2.5, 2.5), Offset(mid - 2.5, size.height - 2.5), hashPaint, ); canvas.drawLine( Offset(mid + 0.5, 2.5), Offset(mid + 0.5, size.height - 2.5), hashPaint, ); canvas.drawLine( Offset(mid + 3.5, 2.5), Offset(mid + 3.5, size.height - 2.5), hashPaint, ); } else { final double mid = size.height / 2; hashPaint.color = darkBackgroundColor; canvas.drawLine( Offset(2.5, mid - 3.5), Offset(size.width - 2.5, mid - 3.5), hashPaint, ); canvas.drawLine( Offset(2.5, mid - 0.5), Offset(size.width - 2.5, mid - 0.5), hashPaint, ); canvas.drawLine( Offset(2.5, mid + 2.5), Offset(size.width - 2.5, mid + 2.5), hashPaint, ); hashPaint.color = brightBackgroundColor; canvas.drawLine( Offset(2.5, mid - 2.5), Offset(size.width - 2.5, mid - 2.5), hashPaint, ); canvas.drawLine( Offset(2.5, mid + 0.5), Offset(size.width - 2.5, mid + 0.5), hashPaint, ); canvas.drawLine( Offset(2.5, mid + 3.5), Offset(size.width - 2.5, mid + 3.5), hashPaint, ); } } @override bool shouldRepaint(CustomPainter oldDelegate) { // TODO: implement shouldRepaint return true; } } @immutable class _AutomaticScrollerParameters { const _AutomaticScrollerParameters(this.direction, this.stopValue); final int direction; final double stopValue; } class _AutomaticScroller { _AutomaticScroller({required this.scrollBar}); final RenderScrollBar scrollBar; Timer? scheduledScrollTimer; static const Duration _delay = Duration(milliseconds: 400); static const Duration _interval = Duration(milliseconds: 30); /// Starts scrolling this skin's scroll bar, stopping the scroll when /// the specified value has been reached. /// /// @param direction /// <tt>1</tt> to adjust the scroll bar's value larger; <tt>-1</tt> to /// adjust it smaller /// /// @param incrementType /// Determines whether we'll use the scroll bar's unit increment or the /// block increment when scrolling /// /// @param stopValue /// The value which, once reached, will stop the automatic scrolling. /// Use <tt>-1</tt> to specify no stop value /// /// @exception IllegalStateException /// If automatic scrolling of any scroll bar is already in progress. /// Only one scroll bar may be automatically scrolled at one time void start(int direction, _ScrollType incrementType, [double? stopValue]) { if (scheduledScrollTimer != null) { throw StateError('Already running'); } scheduledScrollTimer = Timer.periodic(_interval, (Timer timer) { scroll(direction, incrementType, stopValue); }); // We initially scroll once to register that we've started scroll(direction, incrementType, stopValue); } /// Stops any automatic scrolling in progress. void stop() { if (scheduledScrollTimer != null) { scheduledScrollTimer!.cancel(); scheduledScrollTimer = null; } } void scroll(int direction, _ScrollType incrementType, [double? stopValue]) { double start = scrollBar.start; double end = scrollBar.end; double extent = scrollBar.extent; double value = scrollBar.value; double adjustment; if (incrementType == _ScrollType.unit) { adjustment = direction * scrollBar.unitIncrement; } else { adjustment = direction * scrollBar.blockIncrement; } if (adjustment < 0) { double newValue = math.max(value + adjustment, start); scrollBar.value = newValue; if (stopValue != null && newValue < stopValue) { // We've reached the explicit stop value stop(); } if (newValue == start) { // We implicit stop at the minimum scroll bar value stop(); } } else { double newValue = math.min(value + adjustment, end - extent); scrollBar.value = newValue; if (stopValue != null && newValue > stopValue) { // We've reached the explicit stop value stop(); } if (newValue == end - extent) { // We implicitly stop at the maximum scroll bar value stop(); } } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/scroll_pane.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' show log, min, max; import 'package:flutter/gestures.dart'; import 'package:flutter/physics.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'deferred_layout.dart'; import 'listener_list.dart'; import 'scroll_bar.dart'; import 'segment.dart'; /// The policy that dictates how a [ScrollPane] will lay its [ScrollPane.view] /// out within a given [Axis], which directly affects how and when the /// scrollbar is shown in that axis. /// /// See also: /// /// * [ScrollPane.horizontalScrollBarPolicy], which specifies the policy for a /// [ScrollPane]'s horizontal axis. /// * [ScrollPane.verticalScrollBarPolicy], which specifies the policy for a /// [ScrollPane]'s vertical axis. enum ScrollBarPolicy { /// Lays the view out with unconstrained size in the axis, and shows a /// scrollbar only when the viewport's size is less than needed to display /// the entirety of the view. /// /// This policy is somewhat expensive in terms of layout performance. auto, /// Lays the view out with unconstrained size in the axis, and never shows /// a scrollbar, even if the viewport's size is less than needed to display /// the entirety of the view. /// /// The scroll pane will still respond to trackpad / mouse wheel and padding /// (with a touch input) events by scrolling. /// /// Along with the [always] and [stretch] policies, this policy is the /// cheapest in terms of layout performance. never, /// Lays the view out with unconstrained size in the axis, and always shows a /// scrollbar, even if the viewport's size is large enough to display the /// entirety of the view. /// /// If the viewport's size is large enough to display the entirety of the /// view, the scrollbar will be disabled. /// /// Along with the [never] and [stretch] policies, this policy is the /// cheapest in terms of layout performance. always, /// Lays the view out with tight constraints such that the view will be /// exactly the same size in the axis as the viewport's size in that axis. /// /// With this policy, a scrollbar will never be shown because the view is /// always exactly as big as the viewport, even if that size is less than /// the view's intrinsic size. /// /// Along with the [always] and [never] policies, this policy is the /// cheapest in terms of layout performance. stretch, /// Gives the view _at least_ its minimum intrinsic size, and stretches the /// view to match the viewport's size in the axis if there's any excess /// space. /// /// The existence of the scrollbar is the same with this policy as with the /// [auto] policy. The difference between the two policies is that with this /// policy, when the scrollbar is not needed, the view will be stretched to /// exactly fit the size of the viewport in the axis. /// /// This policy is somewhat expensive in terms of layout performance. expand, } /// Signature for a listener function that gets called when a /// [ScrollPaneController]'s scroll offset has changed. /// /// See also: /// * [ScrollPaneListener.onScrollOffsetChanged], the listener property that /// uses this signature. typedef ScrollOffsetChangedHandler = void Function(ScrollPaneController controller, Offset previousOffset); /// An object that will be notified of events fired by [ScrollPaneController]. /// /// Listeners can be registered using [ScrollPaneController.addListener]. class ScrollPaneListener { /// Creates a new [ScrollPaneListener]. const ScrollPaneListener({required this.onScrollOffsetChanged}); /// Listener that will be called when the [ScrollPaneController.scrollOffset] /// changes. final ScrollOffsetChangedHandler onScrollOffsetChanged; } /// A controller for a [ScrollPane]. /// /// A controller can only control one scroll pane at a time. Controllers can be /// attached to a scroll pane by setting them as the [ScrollPane.controller]. /// /// When callers modify values in this class, the attached scroll pane will /// respond, and registered listeners will be notified. class ScrollPaneController with ListenerNotifier<ScrollPaneListener> { /// Creates a new [ScrollPaneController]. /// /// If the `scrollOffset` argument is not specified, it defaults to a zero /// offset. ScrollPaneController({Offset scrollOffset = Offset.zero}) : _scrollOffset = scrollOffset; Offset _scrollOffset; /// The amount that a [ScrollPane.view] has been scrolled within the scroll /// pane's viewport. /// /// An offset of zero indicates that the view's origin (its point in the /// upper-left corner) is drawn at the viewport's origin. A positive /// [Offset.dx] value indicates that the view is translated in the x-axis /// such that its origin exists to the left of the viewport's origin. /// Similarly, a positive [Offset.dy] value indicates that the view is /// translated in the y-axis such that its origin exists above of the /// viewport's origin. /// /// This [Offset.direction] of this scroll offset will always be between zero /// and [pi]/2 (inclusive), meaning that the [Offset.dx] and [Offset.dy] /// values are guaranteed to be greater than or equal to zero. Attempts to /// set an offset with negative values will be fenced. /// /// Changing this value will cause the attached scroll pane (if any) to /// relayout and registered [ScrollPaneListener]s to be notified. Offset get scrollOffset => _scrollOffset; set scrollOffset(Offset value) { value = Offset( min(max(value.dx, 0), _maxScrollLeft), min(max(value.dy, 0), _maxScrollTop), ); if (value == _scrollOffset) return; final Offset previousOffset = _scrollOffset; _scrollOffset = value; notifyListeners((ScrollPaneListener listener) { listener.onScrollOffsetChanged(this, previousOffset); }); } Size _viewportSize = Size.zero; Size _viewSize = Size.zero; void _setRenderValues({ required Size viewSize, required Size viewportSize, required Offset scrollOffset, }) { _viewSize = viewSize; _viewportSize = viewportSize; // This will bounds-check the value and notify listeners. this.scrollOffset = scrollOffset; } double get _maxScrollLeft => max(_viewSize.width - _viewportSize.width, 0); double get _maxScrollTop => max(_viewSize.height - _viewportSize.height, 0); /// The maximum scroll offset given the view size and viewport size. /// /// Attempts to set a [scrollOffset] that's larger than this value will be /// fenced, and this value will be set instead. Offset get maxScrollOffset => Offset(_maxScrollLeft, _maxScrollTop); /// Scrolls this controller until the [scrollOffset] is such that the /// specified `rect` is fully visible in the viewport. /// /// The coordinates of `rect` are in the coordinate space of the viewport /// (the same coordinate space as [scrollOffset]). So if you call this with /// [Rect.zero], this will scroll to a scroll offset of [Offset.zero]. /// /// If the `animation` argument is non-null, the scroll offset will be /// animated to its destination value. Otherwise, the scroll offset will /// jump to its destination. void scrollToVisible(Rect rect, {AnimationController? animation}) { final Rect viewport = scrollOffset & _viewportSize; double deltaX = 0; final double leftDisplacement = rect.left - viewport.left; final double rightDisplacement = rect.right - viewport.right; if (leftDisplacement < 0 && rightDisplacement < 0) { // The area lies to the left of our viewport bounds. deltaX = max(leftDisplacement, rightDisplacement); } else if (leftDisplacement > 0 && rightDisplacement > 0) { // The area lies to the right of our viewport bounds. deltaX = min(leftDisplacement, rightDisplacement); } double deltaY = 0; final double topDisplacement = rect.top - viewport.top; final double bottomDisplacement = rect.bottom - viewport.bottom; if (topDisplacement < 0 && bottomDisplacement < 0) { // The area lies above our viewport bounds. deltaY = max(topDisplacement, bottomDisplacement); } else if (topDisplacement > 0 && bottomDisplacement > 0) { // The area lies below our viewport bounds. deltaY = min(topDisplacement, bottomDisplacement); } if (deltaX != 0 || deltaY != 0) { final Offset target = Offset( min( max(scrollOffset.dx + deltaX, 0), max(_viewSize.width - viewport.width, 0), ), min( max(scrollOffset.dy + deltaY, 0), max(_viewSize.height - viewport.height, 0), ), ); if (animation == null) { scrollOffset = target; } else { _animateTo(target, animation); } } } void _animateTo(Offset target, AnimationController animation) { Animation<Offset> scrollAnimation = Tween<Offset>( begin: scrollOffset, end: target, ).animate(CurvedAnimation(parent: animation, curve: Curves.fastOutSlowIn)); void _handleTick() { scrollOffset = scrollAnimation.value; } void _handleStatusChange(AnimationStatus status) { if (status == AnimationStatus.completed) { scrollAnimation.removeListener(_handleTick); scrollAnimation.removeStatusListener(_handleStatusChange); } } scrollAnimation.addListener(_handleTick); scrollAnimation.addStatusListener(_handleStatusChange); animation.reset(); animation.forward(); } } /// A layout container that provides a scrollable viewport into which a child /// view widget is rendered. class ScrollPane extends StatefulWidget { const ScrollPane({ Key? key, this.horizontalScrollBarPolicy = ScrollBarPolicy.auto, this.verticalScrollBarPolicy = ScrollBarPolicy.auto, this.clipBehavior = Clip.hardEdge, this.controller, this.rowHeader, this.columnHeader, this.topLeftCorner = const _EmptyCorner(), this.bottomLeftCorner = const _EmptyCorner(), this.bottomRightCorner = const _EmptyCorner(), this.topRightCorner = const _EmptyCorner(), required this.view, }) : super(key: key); /// The policy for how to lay the view out and show a scroll bar in the /// horizontal axis. /// /// Must be non-null. Defaults to [ScrollBarPolicy.auto]. final ScrollBarPolicy horizontalScrollBarPolicy; /// The policy for how to lay the view out and show a scroll bar in the /// vertical axis. /// /// Must be non-null. Defaults to [ScrollBarPolicy.auto]. final ScrollBarPolicy verticalScrollBarPolicy; /// The way in which [view], [rowHeader], and [columnHeader] will be clipped. /// /// A scroll pane's contents will always be clipped to the bounds of the /// scroll pane itself. The clip behavior determines how the contents will /// be clipped when they would otherwise overlap each other, the scroll bars, /// or the corners. /// /// Must be non-null; defaults to [Clip.hardEdge], which means that the /// contents of the scroll pane will never be painted over each other. final Clip clipBehavior; /// The controller responsible for managing the scroll offset of this widget. /// /// If this is not provided, one will be created and maintained automatically /// by this widget's [State] object. final ScrollPaneController? controller; /// Optional widget that will be laid out to the left of the view, vertically /// aligned with the top of the view. /// /// The row header will scroll vertically with the scroll pane, but it will /// remain fixed in place in the horizontal axis, even when the view is /// scrolled horizontally. final Widget? rowHeader; /// Optional widget that will be laid out to the top of the view, /// horizontally aligned with the left of the view. /// /// The column header will scroll horizontally with the scroll pane, but it /// will remain fixed in place in the vertical axis, even when the view is /// scrolled vertically. final Widget? columnHeader; /// Optional widget that will be laid out in the top left corner (above the /// row header and to the left of the column header). /// /// If [rowHeader] and [columnHeader] are not both specified, then there is /// no top left corner, and this widget will not be rendered. /// /// If this widget is not specified, and the row header and column header /// are non-null, then a default "empty" corner will be automatically /// created and laid out in this spot. final Widget topLeftCorner; /// Optional widget that will be laid out in the bottom left corner (below /// the row header and to the left of the horizontal scroll bar). /// /// If [rowHeader] is not specified or the horizontal scroll bar is not /// shown, then there is no bottom left corner, and this widget will not be /// rendered. /// /// If this widget is not specified, and a bottom left corner exists, then a /// default "empty" corner will be automatically created and laid out in this /// spot. final Widget bottomLeftCorner; /// Optional widget that will be laid out in the bottom right corner (below /// the vertical scroll bar and to the right of the horizontal scroll bar). /// /// If the scroll bars are not both shown, then there is no bottom right /// corner, and this widget will not be rendered. /// /// If this widget is not specified, and a bottom right corner exists, then a /// default "empty" corner will be automatically created and laid out in this /// spot. final Widget bottomRightCorner; /// Optional widget that will be laid out in the top right corner (above the /// vertical scroll bar and to the right of the column header). /// /// If [columnHeader] is not specified or the vertical scroll bar is not /// shown, then there is no top right corner, and this widget will not be /// rendered. /// /// If this widget is not specified, and a top right corner exists, then a /// default "empty" corner will be automatically created and laid out in this /// spot. final Widget topRightCorner; /// The main scrollable widget to be shown in the viewport of this scroll /// pane. final Widget view; /// Gets the nearest scroll pane ancestor of the specified build context, or /// null if the context doesn't have a scroll pane ancestor. /// /// The given context will _not_ be rebuilt if the scroll pane's scroll /// offset changes. Thus, this method effectively does not introduce a /// dependency on the resulting scroll pane. static ScrollPaneState? of(BuildContext context) { return context .dependOnInheritedWidgetOfExactType<_WriteOnlyScrollPaneScope>() ?.state; } @override ScrollPaneState createState() => ScrollPaneState(); } class ScrollPaneState extends State<ScrollPane> with SingleTickerProviderStateMixin<ScrollPane> { ScrollPaneController? _controller; bool _isUserPanning = false; Animation<Offset>? _panAnimation; late AnimationController _panAnimationController; /// Scrolls the newly focused widget to visible if it's a descendant of a /// scroll pane. void _handleFocusChange() { final BuildContext? focusContext = FocusManager.instance.primaryFocus?.context; if (focusContext != null && ScrollPane.of(focusContext) == this) { // This scroll pane is the nearest ScrollPane ancestor of the widget with // the primary focus. final RenderObject? childRenderObject = focusContext.findRenderObject(); if (childRenderObject is RenderBox) { final ParentData? parentData = childRenderObject.parentData; final Offset offset = parentData is BoxParentData ? parentData.offset : Offset.zero; final Rect childLocation = offset & childRenderObject.size; scrollToVisible(childLocation, context: focusContext); } } } void _resetPanAnimation() { _panAnimation?.removeListener(_handleAnimatePan); _panAnimation = null; _panAnimationController.stop(); _panAnimationController.reset(); } void _handlePanDown(DragDownDetails details) { assert(!_isUserPanning); if (_panAnimationController.isAnimating) { assert(_panAnimation != null); _resetPanAnimation(); } } void _handlePanStart(DragStartDetails details) { assert(!_isUserPanning); assert(!_panAnimationController.isAnimating); assert(_panAnimation == null); if (details.kind == PointerDeviceKind.touch || details.kind == PointerDeviceKind.trackpad) { _isUserPanning = true; } } void _handlePanCancel() { assert(!_panAnimationController.isAnimating); assert(_panAnimation == null); _isUserPanning = false; } void _handlePanUpdate(DragUpdateDetails details) { assert(!_panAnimationController.isAnimating); assert(_panAnimation == null); if (_isUserPanning) { controller.scrollOffset -= details.delta; } } void _handlePanEnd(DragEndDetails details) { if (_isUserPanning) { _isUserPanning = false; final Offset velocity = details.velocity.pixelsPerSecond; if (velocity.distance == 0) { // No need to animate return; } const double drag = 0.0001135; final frictionX = FrictionSimulation( drag, controller.scrollOffset.dx, -velocity.dx, ); final frictionY = FrictionSimulation( drag, controller.scrollOffset.dy, -velocity.dy, ); final Duration duration = _getPanAnimationDuration( velocity.distance, drag, ); _panAnimation = Tween<Offset>( begin: controller.scrollOffset, end: Offset(frictionX.finalX, frictionY.finalX), ).animate( CurvedAnimation( parent: _panAnimationController, curve: Curves.decelerate, ), ); _panAnimationController.duration = duration; _panAnimation!.addListener(_handleAnimatePan); _panAnimationController.forward(); } } /// Given a velocity and drag coefficient, calculate the time at which motion /// will come to a stop, within the margin of effectivelyMotionless. Duration _getPanAnimationDuration(double velocity, double drag) { const double effectivelyMotionless = 10.0; final double seconds = log(effectivelyMotionless / velocity) / log(drag / 100); return Duration(milliseconds: (seconds * 1000).round()); } void _handleAnimatePan() { assert(!_isUserPanning); assert(mounted); assert(_panAnimation != null); final Offset maxScrollOffset = controller.maxScrollOffset; controller.scrollOffset = Offset( min(max(_panAnimation!.value.dx, 0), maxScrollOffset.dx), min(max(_panAnimation!.value.dy, 0), maxScrollOffset.dy), ); if (!_panAnimationController.isAnimating) { return _resetPanAnimation(); } } /// The controller for this scroll pane's offset. ScrollPaneController get controller => widget.controller ?? _controller!; /// Scrolls an area to be visible. /// /// If the `propagate` flag is set to true (the default), this will /// recursively scroll the area in this scroll pane _and all ancestor scroll /// panes_. If the `propagate` flag is false, this will only scroll the area /// to visible in _this_ scroll pane. /// /// If the area is not able to be made entirely visible, then this will /// scroll to reveal as much of the area as possible. /// /// The `rect` argument specifies the area to make visible. /// /// If supplied, the `context` argument specifies a descendant build context /// of the scroll pane that defines the coordinate space of `rect`. If this /// argument is not specified, `rect` will be interpreted as in the /// coordinate space of the scroll pane itself. void scrollToVisible( Rect rect, { BuildContext? context, bool propagate = true, }) { context ??= this.context; final RenderObject? childRenderObject = context.findRenderObject(); final RenderObject? renderScrollPane = this.context.findRenderObject(); assert(childRenderObject != null); assert(renderScrollPane != null); final Matrix4 transform = childRenderObject!.getTransformTo( renderScrollPane!, ); Rect scrollToRect = MatrixUtils.transformRect(transform, rect); if (context != this.context) { scrollToRect = scrollToRect.shift(controller.scrollOffset); } controller.scrollToVisible(scrollToRect); if (propagate) { final Rect adjustedRect = scrollToRect.shift( controller.scrollOffset * -1, ); ScrollPane.of( this.context, )?.scrollToVisible(adjustedRect, context: this.context); } } @override void initState() { super.initState(); FocusManager.instance.addListener(_handleFocusChange); if (widget.controller == null) { _controller = ScrollPaneController(); } _panAnimationController = AnimationController(vsync: this); } @override void didUpdateWidget(ScrollPane oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.controller != widget.controller) { if (oldWidget.controller == null) { assert(_controller != null); _controller!.dispose(); _controller = null; } else { assert(_controller == null); _controller = ScrollPaneController(); } } } @override void dispose() { _panAnimation?.removeListener(_handleAnimatePan); _panAnimation = null; _panAnimationController.dispose(); _controller?.dispose(); FocusManager.instance.removeListener(_handleFocusChange); super.dispose(); } @override Widget build(BuildContext context) { return _WriteOnlyScrollPaneScope( state: this, child: GestureDetector( behavior: HitTestBehavior.translucent, onPanDown: _handlePanDown, onPanStart: _handlePanStart, onPanCancel: _handlePanCancel, onPanUpdate: _handlePanUpdate, onPanEnd: _handlePanEnd, child: _ScrollPane( view: widget.view, rowHeader: widget.rowHeader, columnHeader: widget.columnHeader, topLeftCorner: widget.topLeftCorner, bottomLeftCorner: widget.bottomLeftCorner, bottomRightCorner: widget.bottomRightCorner, topRightCorner: widget.topRightCorner, horizontalScrollBar: const ScrollBar( orientation: Axis.horizontal, unitIncrement: 10, ), verticalScrollBar: const ScrollBar( orientation: Axis.vertical, unitIncrement: 10, ), horizontalScrollBarPolicy: widget.horizontalScrollBarPolicy, verticalScrollBarPolicy: widget.verticalScrollBarPolicy, clipBehavior: widget.clipBehavior, controller: controller, ), ), ); } } /// A scope class that never notifies on update (because it's write-only). class _WriteOnlyScrollPaneScope extends InheritedWidget { const _WriteOnlyScrollPaneScope({required this.state, required Widget child}) : super(child: child); final ScrollPaneState state; @override bool updateShouldNotify(_WriteOnlyScrollPaneScope _) => false; } class _EmptyCorner extends LeafRenderObjectWidget { const _EmptyCorner({Key? key}) : super(key: key); @override RenderObject createRenderObject(BuildContext context) => _RenderEmptyCorner(); } class _RenderEmptyCorner extends RenderBox { static const Color backgroundColor = Color(0xfff0ece7); @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) { return constraints.smallest; } @override void paint(PaintingContext context, Offset offset) { final Paint paint = Paint() ..style = PaintingStyle.fill ..color = backgroundColor; context.canvas.drawRect(offset & size, paint); } } class _ScrollPane extends RenderObjectWidget { const _ScrollPane({ Key? key, required this.view, required this.rowHeader, required this.columnHeader, required this.topLeftCorner, required this.bottomLeftCorner, required this.bottomRightCorner, required this.topRightCorner, required this.horizontalScrollBar, required this.verticalScrollBar, required this.horizontalScrollBarPolicy, required this.verticalScrollBarPolicy, required this.clipBehavior, required this.controller, }) : super(key: key); final Widget view; final Widget? rowHeader; final Widget? columnHeader; final Widget topLeftCorner; final Widget bottomLeftCorner; final Widget bottomRightCorner; final Widget topRightCorner; final Widget horizontalScrollBar; final Widget verticalScrollBar; final ScrollBarPolicy horizontalScrollBarPolicy; final ScrollBarPolicy verticalScrollBarPolicy; final Clip clipBehavior; final ScrollPaneController controller; @override RenderObjectElement createElement() => _ScrollPaneElement(this); @override RenderObject createRenderObject(BuildContext context) { return RenderScrollPane( horizontalScrollBarPolicy: horizontalScrollBarPolicy, verticalScrollBarPolicy: verticalScrollBarPolicy, clipBehavior: clipBehavior, controller: controller, ); } @override void updateRenderObject( BuildContext context, RenderScrollPane renderScrollPane, ) { renderScrollPane ..horizontalScrollBarPolicy = horizontalScrollBarPolicy ..verticalScrollBarPolicy = verticalScrollBarPolicy ..clipBehavior = clipBehavior ..scrollController = controller; } } enum _ScrollPaneSlot { view, rowHeader, columnHeader, topLeftCorner, bottomLeftCorner, bottomRightCorner, topRightCorner, horizontalScrollBar, verticalScrollBar, } class _ScrollPaneElement extends RenderObjectElement { _ScrollPaneElement(_ScrollPane widget) : super(widget); Element? _view; Element? _rowHeader; Element? _columnHeader; Element? _topLeftCorner; Element? _bottomLeftCorner; Element? _bottomRightCorner; Element? _topRightCorner; Element? _horizontalScrollBar; Element? _verticalScrollBar; @override _ScrollPane get widget => super.widget as _ScrollPane; @override RenderScrollPane get renderObject => super.renderObject as RenderScrollPane; @override void update(_ScrollPane newWidget) { super.update(newWidget); assert(widget == newWidget); _updateChildren(newWidget); } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _updateChildren(widget); } void _updateChildren(_ScrollPane widget) { _view = updateChild(_view, widget.view, _ScrollPaneSlot.view); _rowHeader = updateChild( _rowHeader, widget.rowHeader, _ScrollPaneSlot.rowHeader, ); _columnHeader = updateChild( _columnHeader, widget.columnHeader, _ScrollPaneSlot.columnHeader, ); _topLeftCorner = updateChild( _topLeftCorner, widget.topLeftCorner, _ScrollPaneSlot.topLeftCorner, ); _bottomLeftCorner = updateChild( _bottomLeftCorner, widget.bottomLeftCorner, _ScrollPaneSlot.bottomLeftCorner, ); _bottomRightCorner = updateChild( _bottomRightCorner, widget.bottomRightCorner, _ScrollPaneSlot.bottomRightCorner, ); _topRightCorner = updateChild( _topRightCorner, widget.topRightCorner, _ScrollPaneSlot.topRightCorner, ); _horizontalScrollBar = updateChild( _horizontalScrollBar, widget.horizontalScrollBar, _ScrollPaneSlot.horizontalScrollBar, ); _verticalScrollBar = updateChild( _verticalScrollBar, widget.verticalScrollBar, _ScrollPaneSlot.verticalScrollBar, ); } @override void visitChildren(ElementVisitor visitor) { if (_view != null) visitor(_view!); if (_rowHeader != null) visitor(_rowHeader!); if (_columnHeader != null) visitor(_columnHeader!); if (_topLeftCorner != null) visitor(_topLeftCorner!); if (_bottomLeftCorner != null) visitor(_bottomLeftCorner!); if (_bottomRightCorner != null) visitor(_bottomRightCorner!); if (_topRightCorner != null) visitor(_topRightCorner!); if (_horizontalScrollBar != null) visitor(_horizontalScrollBar!); if (_verticalScrollBar != null) visitor(_verticalScrollBar!); } @override void insertRenderObjectChild(RenderBox child, _ScrollPaneSlot slot) { _updateChildSlot(slot, child); } @override void moveRenderObjectChild( RenderObject child, dynamic oldSlot, dynamic newSlot, ) { assert(false); } @override void removeRenderObjectChild(RenderBox child, _ScrollPaneSlot slot) { assert(child.parent == renderObject); _updateChildSlot(slot, null); } void _updateChildSlot(_ScrollPaneSlot slot, RenderBox? child) { switch (slot) { case _ScrollPaneSlot.view: renderObject.view = child; break; case _ScrollPaneSlot.rowHeader: renderObject.rowHeader = child; break; case _ScrollPaneSlot.columnHeader: renderObject.columnHeader = child; break; case _ScrollPaneSlot.topLeftCorner: renderObject.topLeftCorner = child; break; case _ScrollPaneSlot.bottomLeftCorner: renderObject.bottomLeftCorner = child; break; case _ScrollPaneSlot.bottomRightCorner: renderObject.bottomRightCorner = child; break; case _ScrollPaneSlot.topRightCorner: renderObject.topRightCorner = child; break; case _ScrollPaneSlot.horizontalScrollBar: renderObject.horizontalScrollBar = child as RenderScrollBar?; break; case _ScrollPaneSlot.verticalScrollBar: renderObject.verticalScrollBar = child as RenderScrollBar?; break; } } } @immutable class _ScrollPaneViewportResolver implements ViewportResolver { const _ScrollPaneViewportResolver({ required this.constraints, required this.offset, required this.sizeAdjustment, }); final BoxConstraints constraints; final Offset offset; final Offset sizeAdjustment; @override Rect resolve(Size size) { Size viewportSize = constraints.constrain(size + sizeAdjustment) - sizeAdjustment as Size; viewportSize = Size( max(viewportSize.width, 0), max(viewportSize.height, 0), ); return offset & viewportSize; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is _ScrollPaneViewportResolver && other.offset == offset && other.sizeAdjustment == sizeAdjustment && other.constraints == constraints; } @override int get hashCode { return Object.hash(offset, sizeAdjustment, constraints); } @override String toString() { return 'ScrollPaneViewportResolver(viewportOffset=$offset, ' 'sizeAdjustment=$sizeAdjustment, ' 'viewportConstraints=$constraints)'; } } // TODO do we get any benefit to this implementing RenderAbstractViewport? // TODO It looks like RenderAbstractViewport would provide some benefit class RenderScrollPane extends RenderBox with DeferredLayoutMixin { RenderScrollPane({ ScrollBarPolicy horizontalScrollBarPolicy = ScrollBarPolicy.auto, ScrollBarPolicy verticalScrollBarPolicy = ScrollBarPolicy.auto, Clip clipBehavior = Clip.hardEdge, required ScrollPaneController controller, }) : _horizontalScrollBarPolicy = horizontalScrollBarPolicy, _verticalScrollBarPolicy = verticalScrollBarPolicy, _clipBehavior = clipBehavior { _scrollBarValueListener = ScrollBarValueListener( valueChanged: _onScrollBarValueChanged, ); _scrollPaneListener = ScrollPaneListener( onScrollOffsetChanged: _onScrollOffsetChanged, ); this.scrollController = controller; } late final ScrollBarValueListener _scrollBarValueListener; late final ScrollPaneListener _scrollPaneListener; static const double _horizontalReveal = 30; static const double _verticalReveal = 30; static const int _maxLayoutPasses = 4; ScrollBarPolicy _horizontalScrollBarPolicy; ScrollBarPolicy get horizontalScrollBarPolicy => _horizontalScrollBarPolicy; set horizontalScrollBarPolicy(ScrollBarPolicy value) { if (_horizontalScrollBarPolicy == value) return; _horizontalScrollBarPolicy = value; markNeedsLayout(); } ScrollBarPolicy _verticalScrollBarPolicy; ScrollBarPolicy get verticalScrollBarPolicy => _verticalScrollBarPolicy; set verticalScrollBarPolicy(ScrollBarPolicy value) { if (_verticalScrollBarPolicy == value) return; _verticalScrollBarPolicy = value; markNeedsLayout(); } Clip _clipBehavior = Clip.hardEdge; Clip get clipBehavior => _clipBehavior; set clipBehavior(Clip value) { if (_clipBehavior == value) return; _clipBehavior = value; markNeedsPaint(); } ScrollPaneController? _scrollController; ScrollPaneController get scrollController => _scrollController!; set scrollController(ScrollPaneController value) { if (value == _scrollController) return; if (_scrollController != null) { _scrollController!.removeListener(_scrollPaneListener); } _scrollController = value; _scrollController!.addListener(_scrollPaneListener); markNeedsLayout(); } RenderBox? _view; RenderBox? get view => _view; set view(RenderBox? value) { if (value == _view) return; if (_view != null) dropChild(_view!); _view = value; if (_view != null) adoptChild(_view!); } RenderBox? _rowHeader; RenderBox? get rowHeader => _rowHeader; set rowHeader(RenderBox? value) { if (value == _rowHeader) return; if (_rowHeader != null) dropChild(_rowHeader!); _rowHeader = value; if (_rowHeader != null) adoptChild(_rowHeader!); } RenderBox? _columnHeader; RenderBox? get columnHeader => _columnHeader; set columnHeader(RenderBox? value) { if (value == _columnHeader) return; if (_columnHeader != null) dropChild(_columnHeader!); _columnHeader = value; if (_columnHeader != null) adoptChild(_columnHeader!); } RenderBox? _topLeftCorner; RenderBox? get topLeftCorner => _topLeftCorner; set topLeftCorner(RenderBox? value) { if (value == _topLeftCorner) return; if (_topLeftCorner != null) dropChild(_topLeftCorner!); _topLeftCorner = value; if (_topLeftCorner != null) adoptChild(_topLeftCorner!); } RenderBox? _bottomLeftCorner; RenderBox? get bottomLeftCorner => _bottomLeftCorner; set bottomLeftCorner(RenderBox? value) { if (value == _bottomLeftCorner) return; if (_bottomLeftCorner != null) dropChild(_bottomLeftCorner!); _bottomLeftCorner = value; if (_bottomLeftCorner != null) adoptChild(_bottomLeftCorner!); } RenderBox? _bottomRightCorner; RenderBox? get bottomRightCorner => _bottomRightCorner; set bottomRightCorner(RenderBox? value) { if (value == _bottomRightCorner) return; if (_bottomRightCorner != null) dropChild(_bottomRightCorner!); _bottomRightCorner = value; if (_bottomRightCorner != null) adoptChild(_bottomRightCorner!); } RenderBox? _topRightCorner; RenderBox? get topRightCorner => _topRightCorner; set topRightCorner(RenderBox? value) { if (value == _topRightCorner) return; if (_topRightCorner != null) dropChild(_topRightCorner!); _topRightCorner = value; if (_topRightCorner != null) adoptChild(_topRightCorner!); } RenderScrollBar? _horizontalScrollBar; RenderScrollBar? get horizontalScrollBar => _horizontalScrollBar; set horizontalScrollBar(RenderScrollBar? value) { if (value == _horizontalScrollBar) return; if (_horizontalScrollBar != null) { _horizontalScrollBar!.removeListener(_scrollBarValueListener); dropChild(_horizontalScrollBar!); } _horizontalScrollBar = value; if (_horizontalScrollBar != null) { adoptChild(_horizontalScrollBar!); value!.addListener(_scrollBarValueListener); } } RenderScrollBar? _verticalScrollBar; RenderScrollBar? get verticalScrollBar => _verticalScrollBar; set verticalScrollBar(RenderScrollBar? value) { if (value == _verticalScrollBar) return; if (_verticalScrollBar != null) { _verticalScrollBar!.removeListener(_scrollBarValueListener); dropChild(_verticalScrollBar!); } _verticalScrollBar = value; if (_verticalScrollBar != null) { adoptChild(_verticalScrollBar!); value!.addListener(_scrollBarValueListener); } } void _onScrollBarValueChanged( RenderScrollBar scrollBar, double previousValue, ) { final double value = scrollBar.value; if (scrollBar == horizontalScrollBar) { scrollController.scrollOffset = Offset( value, scrollController.scrollOffset.dy, ); } else { scrollController.scrollOffset = Offset( scrollController.scrollOffset.dx, value, ); } } bool _ignoreScrollControllerEvents = false; void _invokeUpdateScrollOffsetCallback(VoidCallback callback) { assert(!_ignoreScrollControllerEvents); _ignoreScrollControllerEvents = true; try { callback(); } finally { _ignoreScrollControllerEvents = false; } } void _onScrollOffsetChanged( ScrollPaneController controller, Offset previousScrollOffset, ) { if (_ignoreScrollControllerEvents) return; assert(controller == scrollController); assert(controller.scrollOffset != previousScrollOffset); final Offset value = controller.scrollOffset; assert(value.dx <= controller._maxScrollLeft); assert(value.dy <= controller._maxScrollTop); horizontalScrollBar!.value = value.dx; verticalScrollBar!.value = value.dy; markNeedsLayout(); } void _onPointerScroll(PointerScrollEvent event) { if ((scrollController.scrollOffset.dx > 0 && event.scrollDelta.dx < 0) || (scrollController.scrollOffset.dy > 0 && event.scrollDelta.dy < 0) || (scrollController.scrollOffset.dx < scrollController._maxScrollLeft && event.scrollDelta.dx > 0) || (scrollController.scrollOffset.dy < scrollController._maxScrollTop && event.scrollDelta.dy > 0)) { GestureBinding.instance.pointerSignalResolver.register(event, ( PointerSignalEvent event, ) { PointerScrollEvent scrollEvent = event as PointerScrollEvent; deferMarkNeedsLayout(() { scrollController.scrollOffset += scrollEvent.scrollDelta; }); }); } } @override void handleEvent(PointerEvent event, HitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (event is PointerScrollEvent) return _onPointerScroll(event); super.handleEvent(event, entry as BoxHitTestEntry); } @override void attach(PipelineOwner owner) { super.attach(owner); view?.attach(owner); rowHeader?.attach(owner); columnHeader?.attach(owner); topLeftCorner?.attach(owner); bottomLeftCorner?.attach(owner); bottomRightCorner?.attach(owner); topRightCorner?.attach(owner); horizontalScrollBar?.attach(owner); verticalScrollBar?.attach(owner); } @override void detach() { super.detach(); view?.detach(); rowHeader?.detach(); columnHeader?.detach(); topLeftCorner?.detach(); bottomLeftCorner?.detach(); bottomRightCorner?.detach(); topRightCorner?.detach(); horizontalScrollBar?.detach(); verticalScrollBar?.detach(); scrollController._setRenderValues( scrollOffset: Offset.zero, viewportSize: Size.zero, viewSize: Size.zero, ); } @override void visitChildren(RenderObjectVisitor visitor) { if (view != null) visitor(view!); if (rowHeader != null) visitor(rowHeader!); if (columnHeader != null) visitor(columnHeader!); if (topLeftCorner != null) visitor(topLeftCorner!); if (bottomLeftCorner != null) visitor(bottomLeftCorner!); if (bottomRightCorner != null) visitor(bottomRightCorner!); if (topRightCorner != null) visitor(topRightCorner!); if (horizontalScrollBar != null) visitor(horizontalScrollBar!); if (verticalScrollBar != null) visitor(verticalScrollBar!); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { // Order is important here; since the corners and scrollbars overlap the // view and headers, they must be hit tested first. final List<RenderBox?> children = <RenderBox?>[ verticalScrollBar, horizontalScrollBar, topRightCorner, bottomRightCorner, bottomLeftCorner, topLeftCorner, columnHeader, rowHeader, view, ]; for (RenderBox? child in children) { if (child != null) { final _ScrollPaneParentData parentData = child.parentData as _ScrollPaneParentData; if (parentData.visible) { final bool isHit = result.addWithPaintOffset( offset: parentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - parentData.offset); return child.hitTest(result, position: transformed); }, ); // We know that RenderScrollPane doesn't overlap its children, so if // one child had a hit, it precludes other children from having had a // hit. Thus we can stop looking for hits after one child reports a hit. if (isHit) { return true; } } } } return false; } @override bool hitTestSelf(Offset position) => true; _ScrollPaneParentData parentDataFor(RenderBox child) => child.parentData as _ScrollPaneParentData; @override void setupParentData(RenderBox child) { if (child.parentData is! _ScrollPaneParentData) child.parentData = _ScrollPaneParentData(); } @override double computeMinIntrinsicWidth(double height) { double preferredWidth = 0; if (view != null) { double preferredRowHeaderWidth = 0; if (rowHeader != null) { preferredRowHeaderWidth = rowHeader!.getMinIntrinsicWidth( double.infinity, ); } double preferredColumnHeaderHeight = 0; if (columnHeader != null) { preferredColumnHeaderHeight = columnHeader!.getMinIntrinsicHeight( double.infinity, ); } ScrollBarPolicy verticalPolicy = verticalScrollBarPolicy; if (verticalPolicy != ScrollBarPolicy.stretch) { // Get the unconstrained preferred size of the view double preferredViewWidth = view!.getMinIntrinsicWidth(double.infinity); double preferredViewHeight = view!.getMinIntrinsicHeight( double.infinity, ); // If the policy is `expand`, and the sum of the // unconstrained preferred heights of the view and the column // header is less than the height constraint, apply the `stretch` // policy; otherwise, apply the `auto` policy if (verticalPolicy == ScrollBarPolicy.expand) { if (height < 0) { verticalPolicy = ScrollBarPolicy.auto; } else { double preferredHeight = preferredViewHeight + preferredColumnHeaderHeight; if (preferredHeight < height) { verticalPolicy = ScrollBarPolicy.stretch; } else { verticalPolicy = ScrollBarPolicy.auto; } } } // If the policy is `always`, `never`, or `auto`, the preferred // width is the sum of the unconstrained preferred widths of // the view and row header, plus the width of the scroll // bar if policy is `always` or if the view's preferred height is // greater than the height constraint and the policy is `auto` if (verticalPolicy == ScrollBarPolicy.always || verticalPolicy == ScrollBarPolicy.never || verticalPolicy == ScrollBarPolicy.auto) { preferredWidth = preferredViewWidth + preferredRowHeaderWidth; // If the sum of the preferred heights of the view and the // column header is greater than the height constraint, // include the preferred width of the scroll bar in the // preferred width calculation if (verticalPolicy == ScrollBarPolicy.always || (verticalPolicy == ScrollBarPolicy.auto && height > 0 && preferredViewHeight + preferredColumnHeaderHeight > height)) { preferredWidth += verticalScrollBar!.getMinIntrinsicWidth( double.infinity, ); } } } if (verticalPolicy == ScrollBarPolicy.stretch) { // Preferred width is the sum of the constrained preferred // width of the view and the unconstrained preferred width of // the row header if (height >= 0) { // Subtract the unconstrained preferred height of the // column header from the height constraint height = max(height - preferredColumnHeaderHeight, 0); } preferredWidth = view!.getMinIntrinsicWidth(height) + preferredRowHeaderWidth; } } return preferredWidth; } @override double computeMaxIntrinsicWidth(double height) => computeMinIntrinsicWidth(height); @override double computeMinIntrinsicHeight(double width) { double preferredHeight = 0; if (view != null) { double preferredRowHeaderWidth = 0; if (rowHeader != null) { preferredRowHeaderWidth = rowHeader!.getMinIntrinsicWidth( double.infinity, ); } double preferredColumnHeaderHeight = 0; if (columnHeader != null) { preferredColumnHeaderHeight = columnHeader!.getMinIntrinsicHeight( double.infinity, ); } ScrollBarPolicy horizontalPolicy = horizontalScrollBarPolicy; if (horizontalPolicy != ScrollBarPolicy.stretch) { // Get the unconstrained preferred size of the view double preferredViewWidth = view!.getMinIntrinsicWidth(double.infinity); double preferredViewHeight = view!.getMinIntrinsicHeight( double.infinity, ); // If the policy is `expand`, and the sum of the // unconstrained preferred widths of the view and the row // header is less than the width constraint, apply the `stretch` // policy; otherwise, apply the `auto` policy if (horizontalPolicy == ScrollBarPolicy.expand) { if (width < 0) { horizontalPolicy = ScrollBarPolicy.auto; } else { double preferredWidth = preferredViewWidth + preferredRowHeaderWidth; if (preferredWidth < width) { horizontalPolicy = ScrollBarPolicy.stretch; } else { horizontalPolicy = ScrollBarPolicy.auto; } } } // If the policy is `always`, `never`, or `auto`, the preferred // height is the sum of the unconstrained preferred heights of // the view and column header, plus the height of the scroll // bar if policy is `always` or if the view's preferred width is // greater than the width constraint and the policy is `auto` if (horizontalPolicy == ScrollBarPolicy.always || horizontalPolicy == ScrollBarPolicy.never || horizontalPolicy == ScrollBarPolicy.auto) { preferredHeight = preferredViewHeight + preferredColumnHeaderHeight; // If the sum of the preferred widths of the view and the // row header is greater than the width constraint, include // the preferred height of the scroll bar in the preferred // height calculation if (horizontalPolicy == ScrollBarPolicy.always || (horizontalPolicy == ScrollBarPolicy.auto && width > 0 && preferredViewWidth + preferredRowHeaderWidth > width)) { preferredHeight += horizontalScrollBar!.getMinIntrinsicHeight( double.infinity, ); } } } if (horizontalPolicy == ScrollBarPolicy.stretch) { // Preferred height is the sum of the constrained preferred height // of the view and the unconstrained preferred height of the column // header if (width >= 0) { // Subtract the unconstrained preferred width of the row header // from the width constraint width = max(width - preferredRowHeaderWidth, 0); } preferredHeight = view!.getMinIntrinsicHeight(width) + preferredColumnHeaderHeight; } } return preferredHeight; } @override double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); @override double? computeDistanceToActualBaseline(TextBaseline baseline) { double? result; double columnHeaderHeight = 0; if (columnHeader != null) { columnHeaderHeight = columnHeader!.size.height; result = columnHeader!.getDistanceToActualBaseline(baseline); } if (result == null && rowHeader != null) { result = rowHeader!.getDistanceToActualBaseline(baseline); if (result != null) { result += columnHeaderHeight; } } if (result == null && view != null) { result = view!.getDistanceToActualBaseline(baseline); if (result != null) { result += columnHeaderHeight; } } return result; } @override void performLayout() { double rowHeaderWidth = 0; if (rowHeader != null) { rowHeaderWidth = rowHeader!.getMaxIntrinsicWidth(double.infinity); } double columnHeaderHeight = 0; if (columnHeader != null) { columnHeaderHeight = columnHeader!.getMaxIntrinsicHeight(double.infinity); } double viewWidth = 0; double viewHeight = 0; double viewportWidth = 0; double viewportHeight = 0; late double previousVerticalScrollBarWidth; late double previousHorizontalScrollBarHeight; double verticalScrollBarWidth = _cachedVerticalScrollBarWidth; double horizontalScrollBarHeight = _cachedHorizontalScrollBarHeight; int i = 0; bool scrollBarSizesChanged() { return horizontalScrollBarHeight != previousHorizontalScrollBarHeight || verticalScrollBarWidth != previousVerticalScrollBarWidth; } do { previousHorizontalScrollBarHeight = horizontalScrollBarHeight; previousVerticalScrollBarWidth = verticalScrollBarWidth; final _ScrollPaneViewportResolver viewportResolver = _ScrollPaneViewportResolver( constraints: constraints, offset: scrollController.scrollOffset, sizeAdjustment: Offset( rowHeaderWidth + verticalScrollBarWidth, columnHeaderHeight + horizontalScrollBarHeight, ), ); if (view != null) { double minWidth = 0; double maxWidth = double.infinity; double minHeight = 0; double maxHeight = double.infinity; switch (horizontalScrollBarPolicy) { case ScrollBarPolicy.stretch: if (constraints.hasBoundedWidth) { minWidth = max( constraints.minWidth - rowHeaderWidth - verticalScrollBarWidth, 0, ); maxWidth = max( constraints.maxWidth - rowHeaderWidth - verticalScrollBarWidth, 0, ); } break; case ScrollBarPolicy.expand: if (constraints.hasBoundedWidth) { minWidth = max( constraints.minWidth - rowHeaderWidth - verticalScrollBarWidth, 0, ); } break; case ScrollBarPolicy.always: case ScrollBarPolicy.auto: case ScrollBarPolicy.never: // Unbounded width constraints break; } switch (verticalScrollBarPolicy) { case ScrollBarPolicy.stretch: if (constraints.hasBoundedHeight) { minHeight = max( constraints.minHeight - columnHeaderHeight - horizontalScrollBarHeight, 0, ); maxHeight = max( constraints.maxHeight - columnHeaderHeight - horizontalScrollBarHeight, 0, ); } break; case ScrollBarPolicy.expand: if (constraints.hasBoundedHeight) { minHeight = max( constraints.minHeight - columnHeaderHeight - horizontalScrollBarHeight, 0, ); } break; case ScrollBarPolicy.always: case ScrollBarPolicy.auto: case ScrollBarPolicy.never: // Unbounded height constraints break; } final SegmentConstraints viewConstraints = SegmentConstraints( minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight, viewportResolver: viewportResolver, ); view!.layout(viewConstraints, parentUsesSize: true); viewWidth = view!.size.width; viewHeight = view!.size.height; } final Rect viewportRect = viewportResolver.resolve( Size(viewWidth, viewHeight), ); viewportWidth = viewportRect.width; viewportHeight = viewportRect.height; if (horizontalScrollBarPolicy == ScrollBarPolicy.always || (horizontalScrollBarPolicy == ScrollBarPolicy.auto && viewWidth > viewportWidth) || (horizontalScrollBarPolicy == ScrollBarPolicy.expand && viewWidth > viewportWidth)) { horizontalScrollBarHeight = horizontalScrollBar!.getMinIntrinsicHeight( double.infinity, ); } else { horizontalScrollBarHeight = 0; } if (verticalScrollBarPolicy == ScrollBarPolicy.always || (verticalScrollBarPolicy == ScrollBarPolicy.auto && viewHeight > viewportHeight) || (verticalScrollBarPolicy == ScrollBarPolicy.expand && viewHeight > viewportHeight)) { verticalScrollBarWidth = verticalScrollBar!.getMinIntrinsicWidth( double.infinity, ); } else { verticalScrollBarWidth = 0; } size = constraints.constrainDimensions( viewportWidth + rowHeaderWidth + verticalScrollBarWidth, viewportHeight + columnHeaderHeight + horizontalScrollBarHeight, ); } while (++i <= RenderScrollPane._maxLayoutPasses && scrollBarSizesChanged()); final double width = size.width; final double height = size.height; _cachedHorizontalScrollBarHeight = horizontalScrollBarHeight; _cachedVerticalScrollBarWidth = verticalScrollBarWidth; if (i > RenderScrollPane._maxLayoutPasses) { assert(() { throw FlutterError( 'A RenderScrollPane exceeded its maximum number of layout cycles.\n' 'RenderScrollPane render objects, during layout, can retry if the introduction ' 'of scrollbars changes the constraints for one of its children.\n' 'In the case of this RenderScrollPane object, however, this happened $RenderScrollPane._maxLayoutPasses ' 'times and still there was no consensus on the constraints. This usually ' 'indicates a bug.', ); }()); } if (columnHeader != null) { final SegmentConstraints columnHeaderConstraints = SegmentConstraints.tightFor( width: viewWidth, height: columnHeaderHeight, viewportResolver: StaticViewportResolver.fromParts( offset: Offset(scrollController.scrollOffset.dx, 0), size: Size(viewportWidth, columnHeaderHeight), ), ); columnHeader!.layout(columnHeaderConstraints, parentUsesSize: true); } if (rowHeader != null) { final SegmentConstraints rowHeaderConstraints = SegmentConstraints.tightFor( width: rowHeaderWidth, height: viewHeight, viewportResolver: StaticViewportResolver.fromParts( offset: Offset(0, scrollController.scrollOffset.dy), size: Size(rowHeaderWidth, viewportHeight), ), ); rowHeader!.layout(rowHeaderConstraints, parentUsesSize: true); } if (columnHeaderHeight > 0 && rowHeaderWidth > 0) { _ScrollPaneParentData parentData = parentDataFor(topLeftCorner!); parentData.offset = Offset.zero; parentData.visible = true; topLeftCorner!.layout( BoxConstraints.tightFor( width: rowHeaderWidth, height: columnHeaderHeight, ), ); } else { topLeftCorner!.layout(BoxConstraints.tight(Size.zero)); parentDataFor(topLeftCorner!).visible = false; } if (rowHeaderWidth > 0 && horizontalScrollBarHeight > 0) { _ScrollPaneParentData parentData = parentDataFor(bottomLeftCorner!); parentData.offset = Offset(0, height - horizontalScrollBarHeight); parentData.visible = true; bottomLeftCorner!.layout( BoxConstraints.tightFor( width: rowHeaderWidth, height: horizontalScrollBarHeight, ), ); } else { bottomLeftCorner!.layout(BoxConstraints.tight(Size.zero)); parentDataFor(bottomLeftCorner!).visible = false; } if (verticalScrollBarWidth > 0 && horizontalScrollBarHeight > 0) { _ScrollPaneParentData parentData = parentDataFor(bottomRightCorner!); parentData.offset = Offset( width - verticalScrollBarWidth, height - horizontalScrollBarHeight, ); parentData.visible = true; bottomRightCorner!.layout( BoxConstraints.tightFor( width: verticalScrollBarWidth, height: horizontalScrollBarHeight, ), ); } else { bottomRightCorner!.layout(BoxConstraints.tight(Size.zero)); parentDataFor(bottomRightCorner!).visible = false; } if (columnHeaderHeight > 0 && verticalScrollBarWidth > 0) { _ScrollPaneParentData parentData = parentDataFor(topRightCorner!); parentData.offset = Offset(width - verticalScrollBarWidth, 0); parentData.visible = true; topRightCorner!.layout( BoxConstraints.tightFor( width: verticalScrollBarWidth, height: columnHeaderHeight, ), ); } else { topRightCorner!.layout(BoxConstraints.tight(Size.zero)); parentDataFor(topRightCorner!).visible = false; } _invokeUpdateScrollOffsetCallback(() { // This will bounds-check the scroll offset. We ignore scroll controller // notifications so as to keep from adjusting the scroll bar values // (we do so below when we lay the scroll bars out) scrollController._setRenderValues( scrollOffset: scrollController.scrollOffset, viewSize: view!.size, viewportSize: Size(viewportWidth, viewportHeight), ); }); // Position the view, row header, and column header only after giving the // scroll controller a chance to bounds-check its scroll offset value. if (view != null) { _ScrollPaneParentData parentData = parentDataFor(view!); parentData.offset = Offset( rowHeaderWidth - scrollController.scrollOffset.dx, columnHeaderHeight - scrollController.scrollOffset.dy, ); parentData.visible = true; } if (columnHeader != null) { _ScrollPaneParentData parentData = parentDataFor(columnHeader!); parentData.offset = Offset( rowHeaderWidth - scrollController.scrollOffset.dx, 0, ); parentData.visible = true; } if (rowHeader != null) { _ScrollPaneParentData parentData = parentDataFor(rowHeader!); parentData.offset = Offset( 0, columnHeaderHeight - scrollController.scrollOffset.dy, ); parentData.visible = true; } // Adjust the structure of our scroll bars. Make sure to do this after we // bounds-check the scroll offset; otherwise we might try to set structure // values that are out of bounds. _ScrollPaneParentData horizontalScrollBarParentData = parentDataFor( horizontalScrollBar!, ); if (viewWidth > 0 && horizontalScrollBarHeight > 0) { horizontalScrollBarParentData.visible = true; horizontalScrollBarParentData.offset = Offset( rowHeaderWidth, height - horizontalScrollBarHeight, ); final double extent = min(viewWidth, viewportWidth); horizontalScrollBar!.blockIncrement = max( 1, viewportWidth - _horizontalReveal, ); horizontalScrollBar!.layout( ScrollBarConstraints.fromBoxConstraints( boxConstraints: BoxConstraints.tightFor( width: viewportWidth, height: horizontalScrollBarHeight, ), enabled: !(scrollController.scrollOffset.dx == 0 && extent == viewWidth), start: 0, end: viewWidth, value: scrollController.scrollOffset.dx, extent: extent, ), parentUsesSize: true, ); } else { horizontalScrollBarParentData.visible = false; horizontalScrollBar!.layout( ScrollBarConstraints.fromBoxConstraints( boxConstraints: BoxConstraints.tight(Size.zero), enabled: horizontalScrollBar!.enabled, start: horizontalScrollBar!.start, end: horizontalScrollBar!.end, value: horizontalScrollBar!.value, extent: horizontalScrollBar!.extent, ), parentUsesSize: true, ); } _ScrollPaneParentData verticalScrollBarParentData = parentDataFor( verticalScrollBar!, ); if (viewHeight > 0 && verticalScrollBarWidth > 0) { verticalScrollBarParentData.visible = true; verticalScrollBarParentData.offset = Offset( width - verticalScrollBarWidth, columnHeaderHeight, ); final double extent = min(viewHeight, viewportHeight); verticalScrollBar!.blockIncrement = max( 1, viewportHeight - _verticalReveal, ); verticalScrollBar!.layout( ScrollBarConstraints.fromBoxConstraints( boxConstraints: BoxConstraints.tightFor( width: verticalScrollBarWidth, height: viewportHeight, ), enabled: !(scrollController.scrollOffset.dy == 0 && extent == viewHeight), start: 0, end: viewHeight, value: scrollController.scrollOffset.dy, extent: extent, ), parentUsesSize: true, ); } else { verticalScrollBarParentData.visible = false; verticalScrollBar!.layout( ScrollBarConstraints.fromBoxConstraints( boxConstraints: BoxConstraints.tight(Size.zero), enabled: verticalScrollBar!.enabled, start: verticalScrollBar!.start, end: verticalScrollBar!.end, value: verticalScrollBar!.value, extent: verticalScrollBar!.extent, ), parentUsesSize: true, ); } } double _cachedHorizontalScrollBarHeight = 0; double _cachedVerticalScrollBarWidth = 0; @override bool get isRepaintBoundary => true; @override void paint(PaintingContext context, Offset offset) { context.pushClipRect( needsCompositing, offset, Offset.zero & size, _paintChildren, ); } void _paintChildren(PaintingContext context, Offset offset) { double rowHeaderWidth = rowHeader?.size.width ?? 0; double columnHeaderHeight = columnHeader?.size.height ?? 0; double viewportWidth = size.width - rowHeaderWidth - verticalScrollBar!.size.width; double viewportHeight = size.height - columnHeaderHeight - horizontalScrollBar!.size.height; if (view != null) { final _ScrollPaneParentData viewParentData = parentDataFor(view!); if (clipBehavior == Clip.none) { context.paintChild(view!, offset + viewParentData.offset); } else { Rect clipRect = Rect.fromLTWH( rowHeaderWidth, columnHeaderHeight, viewportWidth, viewportHeight, ).shift(offset); context.clipRectAndPaint(clipRect, clipBehavior, clipRect, () { context.paintChild(view!, offset + viewParentData.offset); }); } } if (rowHeader != null) { final _ScrollPaneParentData rowHeaderParentData = parentDataFor( rowHeader!, ); if (rowHeaderParentData.visible) { if (clipBehavior == Clip.none) { context.paintChild(rowHeader!, offset + rowHeaderParentData.offset); } else { Rect clipRect = Rect.fromLTWH( 0, columnHeaderHeight, rowHeaderWidth, viewportHeight, ).shift(offset); context.clipRectAndPaint(clipRect, clipBehavior, clipRect, () { context.paintChild(rowHeader!, offset + rowHeaderParentData.offset); }); } } } if (columnHeader != null) { final _ScrollPaneParentData columnHeaderParentData = parentDataFor( columnHeader!, ); if (columnHeaderParentData.visible) { if (clipBehavior == Clip.none) { context.paintChild( columnHeader!, offset + columnHeaderParentData.offset, ); } else { Rect clipRect = Rect.fromLTWH( rowHeaderWidth, 0, viewportWidth, columnHeaderHeight, ).shift(offset); context.clipRectAndPaint(clipRect, clipBehavior, clipRect, () { context.paintChild( columnHeader!, offset + columnHeaderParentData.offset, ); }); } } } _ScrollPaneParentData horizontalScrollBarParentData = parentDataFor( horizontalScrollBar!, ); if (horizontalScrollBarParentData.visible) { context.paintChild( horizontalScrollBar!, offset + horizontalScrollBarParentData.offset, ); } _ScrollPaneParentData verticalScrollBarParentData = parentDataFor( verticalScrollBar!, ); if (verticalScrollBarParentData.visible) { context.paintChild( verticalScrollBar!, offset + verticalScrollBarParentData.offset, ); } _ScrollPaneParentData topLeftCornerParentData = parentDataFor( topLeftCorner!, ); if (topLeftCornerParentData.visible) { context.paintChild( topLeftCorner!, offset + topLeftCornerParentData.offset, ); } _ScrollPaneParentData bottomLeftCornerParentData = parentDataFor( bottomLeftCorner!, ); if (bottomLeftCornerParentData.visible) { context.paintChild( bottomLeftCorner!, offset + bottomLeftCornerParentData.offset, ); } _ScrollPaneParentData bottomRightCornerParentData = parentDataFor( bottomRightCorner!, ); if (bottomRightCornerParentData.visible) { context.paintChild( bottomRightCorner!, offset + bottomRightCornerParentData.offset, ); } _ScrollPaneParentData topRightCornerParentData = parentDataFor( topRightCorner!, ); if (topRightCornerParentData.visible) { context.paintChild( topRightCorner!, offset + topRightCornerParentData.offset, ); } } @override void redepthChildren() { if (view != null) redepthChild(view!); if (rowHeader != null) redepthChild(rowHeader!); if (columnHeader != null) redepthChild(columnHeader!); if (topLeftCorner != null) redepthChild(topLeftCorner!); if (bottomLeftCorner != null) redepthChild(bottomLeftCorner!); if (bottomRightCorner != null) redepthChild(bottomRightCorner!); if (topRightCorner != null) redepthChild(topRightCorner!); if (horizontalScrollBar != null) redepthChild(horizontalScrollBar!); if (verticalScrollBar != null) redepthChild(verticalScrollBar!); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> result = <DiagnosticsNode>[]; void add(RenderBox? child, String name) { if (child != null) result.add(child.toDiagnosticsNode(name: name)); } add(view, 'view'); add(rowHeader, 'rowHeader'); add(columnHeader, 'columnHeader'); add(topLeftCorner, 'topLeftCorner'); add(bottomLeftCorner, 'bottomLeftCorner'); add(bottomRightCorner, 'bottomRightCorner'); add(topRightCorner, 'topRightCorner'); add(horizontalScrollBar, 'horizontalScrollBar'); add(verticalScrollBar, 'verticalScrollBar'); return result; } } class _ScrollPaneParentData extends BoxParentData { bool visible = true; }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/segment.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; /// Class that serves as the defining property of [SegmentConstraints]. /// /// This allows callers to find out what the parent's viewport will be given a /// child's size. Classes that are set as the [ScrollPane.view] will be passed /// [SegmentConstraints] and can use the [SegmentConstraints.viewportResolver] /// to optimize their building, layout, and/or painting. @immutable abstract class ViewportResolver { Rect resolve(Size size); } /// A [ViewportResolver] whose viewport does not depend on the size passed to /// [resolve]. class StaticViewportResolver implements ViewportResolver { const StaticViewportResolver(this.viewport); StaticViewportResolver.fromParts({required Offset offset, required Size size}) : viewport = offset & size; final Rect viewport; @override Rect resolve(Size size) => viewport; @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is StaticViewportResolver && other.viewport == viewport; } @override int get hashCode => viewport.hashCode; @override String toString() { return 'StaticViewportResolver(viewport=$viewport)'; } } /// Constraints that are passed by [RenderScrollPane]. /// /// Segment constraints are specialized box constraints; in addition to the /// basic box constraints properties, they provide a [ViewportResolver], which /// tells the child what the scroll pane's viewport will be given the child's /// size. class SegmentConstraints extends BoxConstraints { const SegmentConstraints({ double minWidth = 0, double maxWidth = double.infinity, double minHeight = 0, double maxHeight = double.infinity, required this.viewportResolver, }) : super( minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight, ); SegmentConstraints.tightFor({ double? width, double? height, required this.viewportResolver, }) : super.tightFor(width: width, height: height); final ViewportResolver viewportResolver; BoxConstraints asBoxConstraints() { return BoxConstraints( minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight, ); } @override BoxConstraints deflate(EdgeInsetsGeometry edges) { final BoxConstraints baseConstraints = super.deflate(edges); return SegmentConstraints( minWidth: baseConstraints.minWidth, maxWidth: baseConstraints.maxWidth, minHeight: baseConstraints.minHeight, maxHeight: baseConstraints.maxHeight, viewportResolver: viewportResolver, // TODO adjust resolver? ); } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is SegmentConstraints && super == other && other.viewportResolver == viewportResolver; } @override int get hashCode { assert(debugAssertIsValid()); return Object.hash(super.hashCode, viewportResolver); } @override String toString() { return 'SegmentConstraints(base=${super.toString()}, viewportResolver=$viewportResolver)'; } } abstract class RenderSegment extends RenderBox { void _debugCheckConstraints(Constraints constraints) { assert(() { if (constraints is! SegmentConstraints) { FlutterError.reportError( FlutterErrorDetails( exception: 'RenderSegment was given constraints other than SegmentConstraints', stack: StackTrace.current, library: 'chicago', ), ); } return true; }()); } @override SegmentConstraints get constraints { final BoxConstraints constraints = super.constraints; _debugCheckConstraints(constraints); return constraints as SegmentConstraints; } @override void layout(Constraints constraints, {bool parentUsesSize = false}) { _debugCheckConstraints(constraints); super.layout(constraints, parentUsesSize: parentUsesSize); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/set_baseline.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; class SetBaseline extends SingleChildRenderObjectWidget { SetBaseline({Key? key, required Widget child, required this.baseline}) : super(key: key, child: child); final double baseline; @override RenderObject createRenderObject(BuildContext context) { return RenderSetBaseline(baseline: baseline); } @override void updateRenderObject( BuildContext context, RenderSetBaseline renderObject, ) { renderObject.baseline = baseline; } } class RenderSetBaseline extends RenderBox with RenderObjectWithChildMixin<RenderBox> { RenderSetBaseline({required double baseline}) { this.baseline = baseline; } double? _baseline; double get baseline => _baseline!; set baseline(double value) { if (value == _baseline) return; _baseline = value; markNeedsLayout(); } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { return this.baseline; } @override double computeMinIntrinsicWidth(double height) { return child == null ? 0 : child!.getMinIntrinsicWidth(height); } @override double computeMaxIntrinsicWidth(double height) { return child == null ? 0 : child!.getMaxIntrinsicWidth(height); } @override double computeMinIntrinsicHeight(double width) { return child == null ? 0 : child!.getMinIntrinsicHeight(width); } @override double computeMaxIntrinsicHeight(double width) { return child == null ? 0 : child!.getMaxIntrinsicHeight(width); } @override void performLayout() { if (child != null) { child!.layout(constraints, parentUsesSize: true); size = child!.size; } else { performResize(); } } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { if (child == null) return false; return child!.hitTest(result, position: position); } @override void paint(PaintingContext context, Offset offset) { if (child != null) { context.paintChild(child!, offset); } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/sheet.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:flutter/material.dart' show Material, MaterialType, Theme, ThemeData; import 'push_button.dart'; import 'foundation.dart'; class Sheet extends StatelessWidget { const Sheet({ Key? key, required this.content, this.padding = const EdgeInsets.all(8), }) : super(key: key); final Widget content; final EdgeInsetsGeometry padding; @override Widget build(BuildContext context) { return Material( type: MaterialType.canvas, color: const Color(0xebf6f4ed), elevation: 4, child: DecoratedBox( decoration: const BoxDecoration( border: Border.fromBorderSide( BorderSide(color: const Color(0xff999999)), ), ), child: Padding( padding: const EdgeInsets.all(1), child: DecoratedBox( decoration: const BoxDecoration( border: Border(bottom: BorderSide(color: Color(0xffdedcd5))), ), child: Padding(padding: padding, child: content), ), ), ), ); } static Future<T?> open<T>({ required BuildContext context, required Widget content, EdgeInsetsGeometry padding = const EdgeInsets.all(8), Color barrierColor = const Color(0x80000000), bool barrierDismissible = false, }) { return DialogTracker<T>().open( context: context, barrierDismissible: barrierDismissible, barrierColor: barrierColor, child: Sheet(padding: padding, content: content), ); } } class Prompt extends StatelessWidget { const Prompt({ Key? key, required this.messageType, required this.message, required this.body, this.options = const <String>[], this.selectedOption, }) : super(key: key); final MessageType messageType; final String message; final Widget body; final List<String> options; final int? selectedOption; void _setSelectedOption(BuildContext context, int index) { Navigator.of(context).pop<int>(index); } @override Widget build(BuildContext context) { return Sheet( content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: [ DecoratedBox( decoration: BoxDecoration( color: const Color(0xffffffff), border: Border.all(color: const Color(0xff999999)), ), child: Padding( padding: EdgeInsets.all(13), child: SizedBox( width: 280, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ messageType.toImage(), Expanded( child: Padding( padding: EdgeInsets.only(left: 12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( message, style: Theme.of(context).textTheme.bodyMedium! .copyWith(fontWeight: FontWeight.bold), ), Padding( padding: EdgeInsets.only(top: 11), child: body, ), ], ), ), ), ], ), ), ), ), Padding( padding: EdgeInsets.only(top: 8), child: Row( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: List<Widget>.generate(options.length, (int index) { return Padding( padding: EdgeInsets.only(left: 4), child: CommandPushButton( onPressed: () => _setSelectedOption(context, index), label: options[index], autofocus: index == selectedOption, ), ); }), ), ), ], ), ); } static Future<int> open({ required BuildContext context, required MessageType messageType, required String message, required Widget body, List<String> options = const <String>[], int? selectedOption, }) async { final int? result = await DialogTracker<int>().open( context: context, barrierDismissible: false, child: Prompt( messageType: messageType, message: message, body: body, options: options, selectedOption: selectedOption, ), ); return result!; } } /// Tracks the open/close animation of a dialog, allowing callers to open a /// dialog and get notified when the dialog fully closes (closing animation /// completes) rather than simply when the modal route is popped (closing /// animation starts) @visibleForTesting class DialogTracker<T> { final Completer<T?> _completer = Completer<T?>(); Animation<double>? _animation; bool _isDialogClosing = false; _AsyncResult<T>? _result; Future<T?> open({ required BuildContext context, bool barrierDismissible = true, String barrierLabel = 'Dismiss', Color barrierColor = const Color(0x80000000), required Widget child, }) { final ThemeData theme = Theme.of(context); showGeneralDialog<T>( context: context, barrierDismissible: barrierDismissible, barrierLabel: barrierLabel, barrierColor: barrierColor, pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) { return Theme(data: theme, child: child); }, transitionDuration: const Duration(milliseconds: 300), transitionBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) { assert(_animation == null || _animation == animation); if (_animation == null) { _animation = animation; animation.addStatusListener(_handleAnimationStatusUpdate); } return Align( alignment: Alignment.topCenter, child: SlideTransition( position: Tween<Offset>( begin: Offset(0, -1), end: Offset.zero, ).animate( CurvedAnimation(parent: animation, curve: Curves.easeOut), ), child: child, ), ); }, ) .then((T? value) { _result = _AsyncResult<T>.value(value); }) .catchError((dynamic error, StackTrace stack) { _result = _AsyncResult<T>.error(error, stack); }); return _completer.future; } void _handleAnimationStatusUpdate(AnimationStatus status) { if (!_isDialogClosing && status == AnimationStatus.reverse) { _isDialogClosing = true; } if (_isDialogClosing && status == AnimationStatus.dismissed) { assert(_result != null); assert(!_completer.isCompleted); _isDialogClosing = false; _animation!.removeStatusListener(_handleAnimationStatusUpdate); _animation = null; _result!.complete(_completer); } } } class _AsyncResult<T> { const _AsyncResult.value(this.value) : error = null, stack = null; const _AsyncResult.error(Object this.error, StackTrace this.stack) : value = null; final T? value; final Object? error; final StackTrace? stack; void complete(Completer<T?> completer) { if (error != null) { completer.completeError(error!, stack); } else { completer.complete(value); } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/sorting.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/rendering.dart'; enum SortDirection { ascending, descending } class SortIndicatorPainter extends CustomPainter { const SortIndicatorPainter({ required this.sortDirection, this.isAntiAlias = true, this.color = const Color(0xff999999), }); final SortDirection sortDirection; final bool isAntiAlias; final Color color; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = color ..isAntiAlias = isAntiAlias; Path path = Path(); const double zero = 0; final double x1 = (size.width - 1) / 2; final double x2 = size.width - 1; final double y1 = size.height - 1; switch (sortDirection) { case SortDirection.ascending: path ..moveTo(zero, y1) ..lineTo(x1, zero) ..lineTo(x2, y1); break; case SortDirection.descending: path ..moveTo(zero, zero) ..lineTo(x1, y1) ..lineTo(x2, zero); break; } path.close(); paint.style = PaintingStyle.stroke; canvas.drawPath(path, paint); paint.style = PaintingStyle.fill; canvas.drawPath(path, paint); } @override bool shouldRepaint(CustomPainter old) { assert(old is SortIndicatorPainter); SortIndicatorPainter oldPainter = old as SortIndicatorPainter; return sortDirection != oldPainter.sortDirection; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/span.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'foundation.dart'; /// Class representing a range of integer values. The range includes all /// values in the interval `[start, end]`. Values may be negative, and the /// value of [start] may be less than, equal to, or greater than the value /// of [end]. class Span { const Span(this.start, this.end); const Span.single(this.start) : end = start; Span.normalized(int start, int end) : this.start = math.min(start, end), this.end = math.max(start, end); final int start; final int end; Span copyWith({int? start, int? end}) { return Span(start ?? this.start, end ?? this.end); } int get length => (end - start).abs() + 1; bool contains(Span span) { final Span normalizedSpan = span.normalize(); if (start < end) { return start <= normalizedSpan.start && end >= normalizedSpan.end; } else { return end <= normalizedSpan.start && start >= normalizedSpan.end; } } bool intersects(Span span) { final Span normalizedSpan = span.normalize(); if (start < end) { return start <= normalizedSpan.end && end >= normalizedSpan.start; } else { return end <= normalizedSpan.end && start >= normalizedSpan.start; } } Span? intersect(Span span) { return intersects(span) ? Span(math.max(start, span.start), math.min(end, span.end)) : null; } Span union(Span span) { return Span(math.min(start, span.start), math.max(end, span.end)); } /// Whether [start] is less than or equal to [end]. /// /// See also: /// * [normalize], which returns a new span that is guaranteed to be /// normalized. bool get isNormalized => start <= end; /// Returns a span with the same range as this span but in which [start] is /// guaranteed to be less than or equal to [end]. Span normalize() => Span(math.min(start, end), math.max(start, end)); /// Returns this span's range as an iterable collection of integers. /// /// If this span's [start] is less than its [end], the returned iterable will /// produce increasing values. If its [start] is greater than its [end], the /// returned iterable will produce decreasing values. Iterable<int> asIterable() => Iterable<int>.generate(length, (int index) { if (end >= start) { return start + index; } else { return start - index; } }); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is Span && other.start == start && other.end == end; } @override int get hashCode => Object.hash(start, end); @override String toString() => '$runtimeType(start=$start,end=$end)'; } class ListSelection { List<Span> _ranges = <Span>[]; /// Comparator that determines the index of the first intersecting range. int _compareStart(Span a, Span b) => a.end - b.start; /// Comparator that determines the index of the last intersecting range. int _compareEnd(Span a, Span b) => a.start - b.end; /// Comparator that determines if two ranges intersect. int _compareIntersection(Span a, Span b) => (a.start > b.end) ? 1 : (b.start > a.end) ? -1 : 0; /// Adds a range to this list, merging and removing intersecting ranges as /// needed. List<Span> addRange(int start, int end) { List<Span> addedRanges = <Span>[]; Span range = Span.normalized(start, end); assert(range.start >= 0); int n = _ranges.length; if (n == 0) { // The selection is currently empty; append the new range // and add it to the added range list _ranges.add(range); addedRanges.add(range); } else { // Locate the lower bound of the intersection int i = binarySearch<Span>(_ranges, range, compare: _compareStart); if (i < 0) { i = -(i + 1); } // Merge the selection with the previous range, if necessary if (i > 0) { Span previousRange = _ranges[i - 1]; if (range.start == previousRange.end + 1) { i--; } } if (i == n) { // The new range starts after the last existing selection // ends; append it and add it to the added range list _ranges.add(range); addedRanges.add(range); } else { // Locate the upper bound of the intersection int j = binarySearch(_ranges, range, compare: _compareEnd); if (j < 0) { j = -(j + 1); } else { j++; } // Merge the selection with the next range, if necessary if (j < n) { Span nextRange = _ranges[j]; if (range.end == nextRange.start - 1) { j++; } } if (i == j) { _ranges.insert(i, range); addedRanges.add(range); } else { // Create a new range representing the union of the intersecting ranges Span lowerRange = _ranges[i]; Span upperRange = _ranges[j - 1]; range = Span( math.min(range.start, lowerRange.start), math.max(range.end, upperRange.end), ); // Add the gaps to the added list if (range.start < lowerRange.start) { addedRanges.add(Span(range.start, lowerRange.start - 1)); } for (int k = i; k < j - 1; k++) { Span selectedRange = _ranges[k]; Span nextSelectedRange = _ranges[k + 1]; addedRanges.add( Span(selectedRange.end + 1, nextSelectedRange.start - 1), ); } if (range.end > upperRange.end) { addedRanges.add(Span(upperRange.end + 1, range.end)); } // Remove all redundant ranges _ranges[i] = range; if (i < j) { _ranges.removeRange(i + 1, j); } } } } return addedRanges; } List<Span> removeRange(int start, int end) { List<Span> removedRanges = <Span>[]; Span range = Span.normalized(start, end); assert(range.start >= 0); int n = _ranges.length; if (n > 0) { // Locate the lower bound of the intersection int i = binarySearch<Span>(_ranges, range, compare: _compareStart); if (i < 0) { i = -(i + 1); } if (i < n) { Span lowerRange = _ranges[i]; if (lowerRange.start < range.start && lowerRange.end > range.end) { // Removing the range will split the intersecting selection // into two ranges _ranges[i] = Span(lowerRange.start, range.start - 1); _ranges.insert(i + 1, Span(range.end + 1, lowerRange.end)); removedRanges.add(range); } else { Span? leadingRemovedRange; if (range.start > lowerRange.start) { // Remove the tail of this range _ranges[i] = Span(lowerRange.start, range.start - 1); leadingRemovedRange = Span(range.start, lowerRange.end); i++; } // Locate the upper bound of the intersection int j = binarySearch<Span>(_ranges, range, compare: _compareEnd); if (j < 0) { j = -(j + 1); } else { j++; } if (j > 0) { Span upperRange = _ranges[j - 1]; Span? trailingRemovedRange; if (range.end < upperRange.end) { // Remove the head of this range _ranges[j - 1] = Span(range.end + 1, upperRange.end); trailingRemovedRange = Span(upperRange.start, range.end); j--; } // Remove all cleared ranges List<Span> clearedRanges = _ranges.sublist(i, j); _ranges.removeRange(i, j); // Construct the removed range list if (leadingRemovedRange != null) { removedRanges.add(leadingRemovedRange); } for (int k = 0, c = clearedRanges.length; k < c; k++) { removedRanges.add(clearedRanges[k]); } if (trailingRemovedRange != null) { removedRanges.add(trailingRemovedRange); } } } } } return removedRanges; } void clear() => _ranges.clear(); Span operator [](int index) => _ranges[index]; int get length => _ranges.length; bool get isEmpty => length == 0; bool get isNotEmpty => length > 0; Span get first => _ranges.first; Span get last => _ranges.last; Iterable<Span> get data => _ranges; int indexOf(Span span) { final int i = binarySearch<Span>( _ranges, span, compare: _compareIntersection, ); if (i >= 0) { return span == _ranges[i] ? i : -1; } return -1; } bool containsIndex(int index) { final Span span = Span.single(index); final int i = binarySearch(_ranges, span, compare: _compareIntersection); return (i >= 0); } /// Inserts an index into the span sequence (e.g. when items are inserted into the model data). void insertIndex(int index) { // Get the insertion point for the range corresponding to the given index Span range = Span.single(index); int i = binarySearch(_ranges, range, compare: _compareIntersection); if (i < 0) { // The inserted index does not intersect with a selected range i = -(i + 1); } else { // The inserted index intersects with a currently selected range Span selectedRange = _ranges[i]; // If the inserted index falls within the current range, increment // the endpoint only if (selectedRange.start < index) { _ranges[i] = Span(selectedRange.start, selectedRange.end + 1); // Start incrementing range bounds beginning at the next range i++; } } // Increment any subsequent selection indexes int n = _ranges.length; while (i < n) { Span selectedRange = _ranges[i]; _ranges[i] = Span(selectedRange.start + 1, selectedRange.end + 1); i++; } } /// Removes a range of indexes from the span sequence (e.g. when items are removed from the model data). void removeIndexes(int index, int count) { // Clear any selections in the given range removeRange(index, (index + count) - 1); // Decrement any subsequent selection indexes final Span range = Span.single(index); int i = binarySearch(_ranges, range, compare: _compareIntersection); assert( i < 0, 'i should be negative, since index should no longer be selected', ); i = -(i + 1); // Determine the number of ranges to modify int n = _ranges.length; while (i < n) { Span selectedRange = _ranges[i]; _ranges[i] = Span(selectedRange.start - count, selectedRange.end - count); i++; } } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/spinner.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; import 'focus_indicator.dart'; import 'hover_builder.dart'; import 'widget_surveyor.dart'; typedef SpinnerItemBuilder = Widget Function(BuildContext context, int index, bool isEnabled); class _Worker { _Worker(this._spinner, this._controller); Spinner _spinner; SpinnerController _controller; Timer? _timer; static const Duration _delay = Duration(milliseconds: 400); static const Duration _period = Duration(milliseconds: 30); void start(int direction) { if (_timer != null) { // Already running return; } // Wait a timeout period, then begin rapidly spinning _timer = Timer(_delay, () { _timer = Timer.periodic(_period, (Timer timer) { assert(() { if (_controller._debugDisposed) { stop(); throw FlutterError( 'A ${_controller.runtimeType} was used after being disposed.\n' 'Once you have called dispose() on an object, it can no longer be used.', ); } return true; }()); spin(direction); }); }); // We initially spin once to register that we've started spin(direction); } void stop() { if (_timer != null) { _timer!.cancel(); _timer = null; } } void spin(int direction) { final bool circular = _spinner.isCircular; final int length = _spinner.length; if (direction > 0) { if (_controller.selectedIndex < length - 1) { _controller.selectedIndex++; } else if (circular) { _controller.selectedIndex = 0; } else { stop(); } } else { if (_controller.selectedIndex > 0) { _controller.selectedIndex--; } else if (circular) { _controller.selectedIndex = length - 1; } else { stop(); } } } void _didUpdateWidget(Spinner spinner, SpinnerController controller) { this._spinner = spinner; this._controller = controller; } } class SpinnerController extends ChangeNotifier { SpinnerController(); SpinnerController._withIndex(this._index); bool _debugDisposed = false; void dispose() { assert(() { _debugDisposed = true; return true; }()); super.dispose(); } int _index = -1; int get selectedIndex => _index; set selectedIndex(int value) { assert(value >= 0); _index = value; notifyListeners(); } } class Spinner extends StatefulWidget { const Spinner({ Key? key, required this.length, required this.itemBuilder, this.controller, this.isEnabled = true, this.isCircular = false, this.sizeToContent = false, this.semanticLabel, }) : super(key: key); final int length; final SpinnerItemBuilder itemBuilder; final SpinnerController? controller; final bool isEnabled; final bool isCircular; final bool sizeToContent; final String? semanticLabel; static Widget defaultItemBuilder(BuildContext context, String value) { return Builder( builder: (BuildContext context) { final TextStyle style = DefaultTextStyle.of(context).style; final TextDirection textDirection = Directionality.of(context); return Padding( padding: EdgeInsets.all(2), child: Align( alignment: Alignment.centerLeft, child: Text( value, maxLines: 1, softWrap: false, textDirection: textDirection, style: style, ), ), ); }, ); } @override _SpinnerState createState() => _SpinnerState(); } class _SpinnerState extends State<Spinner> { FocusNode? _focusNode; bool _isFocused = false; SpinnerController? _controller; late _Worker _worker; int _index = -1; double? _contentWidth; SpinnerController get controller => widget.controller ?? _controller!; int _boundsCheckIndex() { return controller.selectedIndex < widget.length ? controller.selectedIndex : -1; } void _handleSelectedIndexUpdated() { setState(() { _index = _boundsCheckIndex(); }); } void _updateContentWidth() { if (!widget.sizeToContent) { _contentWidth = null; } else { final TextDirection textDirection = Directionality.of(context); final TextStyle style = DefaultTextStyle.of(context).style; const WidgetSurveyor surveyor = WidgetSurveyor(); double maxWidth = 0; for (int i = 0; i < widget.length; i++) { Widget item = Directionality( textDirection: textDirection, child: DefaultTextStyle( style: style, child: widget.itemBuilder(context, i, widget.isEnabled), ), ); final Size itemSize = surveyor.measureWidget(item); maxWidth = math.max(maxWidth, itemSize.width); } _contentWidth = maxWidth; } } void _handleFocusChange(bool hasFocus) { setState(() { _isFocused = hasFocus; }); } KeyEventResult _handleKey(FocusNode node, KeyEvent event) { assert(widget.isEnabled); if (event.logicalKey == LogicalKeyboardKey.arrowDown) { if (event is KeyDownEvent) { _worker.start(-1); } else { _worker.stop(); } return KeyEventResult.handled; } else if (event.logicalKey == LogicalKeyboardKey.arrowUp) { if (event is KeyDownEvent) { _worker.start(1); } else { _worker.stop(); } return KeyEventResult.handled; } else { return KeyEventResult.ignored; } } void _requestFocus() { _focusNode!.requestFocus(); } @override void initState() { super.initState(); _focusNode = FocusNode(canRequestFocus: widget.isEnabled); if (widget.controller == null) { _controller = SpinnerController(); } controller.addListener(_handleSelectedIndexUpdated); _worker = _Worker(widget, controller); _index = _boundsCheckIndex(); } @override void didChangeDependencies() { super.didChangeDependencies(); _updateContentWidth(); } @override void didUpdateWidget(Spinner oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.controller != widget.controller) { if (widget.controller == null) { assert(oldWidget.controller != null); assert(_controller == null); _controller = SpinnerController._withIndex( oldWidget.controller!.selectedIndex, ); } if (oldWidget.controller == null) { assert(widget.controller != null); assert(_controller != null); _controller!.dispose(); _controller = null; } } _focusNode!.canRequestFocus = widget.isEnabled; _worker._didUpdateWidget(widget, controller); _index = _boundsCheckIndex(); _updateContentWidth(); } @override void dispose() { controller.removeListener(_handleSelectedIndexUpdated); if (_controller != null) { assert(widget.controller == null); _controller!.dispose(); } _focusNode?.dispose(); _focusNode = null; super.dispose(); } @override Widget build(BuildContext context) { Widget content = widget.itemBuilder(context, _index, widget.isEnabled); if (widget.sizeToContent) { content = SizedBox(width: _contentWidth, child: content); } content = GestureDetector( onTap: widget.isEnabled ? _requestFocus : null, child: Focus( focusNode: _focusNode, onKeyEvent: widget.isEnabled ? _handleKey : null, onFocusChange: _handleFocusChange, child: Semantics( enabled: widget.isEnabled, focusable: widget.isEnabled, focused: _focusNode!.hasFocus, label: widget.semanticLabel ?? 'Spinner', onIncrease: () => _worker.spin(1), onDecrease: () => _worker.spin(-1), child: Padding( padding: EdgeInsets.all(1), child: FocusIndicator(isFocused: _isFocused, child: content), ), ), ), ); content = ColoredBox(color: const Color(0xffffffff), child: content); return _RawSpinner( content: content, upButton: _SpinnerButton( worker: _worker, direction: 1, onTapDown: _requestFocus, isEnabled: widget.isEnabled, ), downButton: _SpinnerButton( worker: _worker, direction: -1, onTapDown: _requestFocus, isEnabled: widget.isEnabled, ), ); } } class _SpinnerButton extends StatefulWidget { const _SpinnerButton({ Key? key, required this.worker, required this.direction, required this.onTapDown, required this.isEnabled, }) : super(key: key); final _Worker worker; final int direction; final VoidCallback onTapDown; final bool isEnabled; @override _SpinnerButtonState createState() => _SpinnerButtonState(); } class _SpinnerButtonState extends State<_SpinnerButton> { bool _pressed = false; void _handleTapDown(TapDownDetails details) { setState(() => _pressed = true); widget.worker.start(widget.direction); widget.onTapDown(); } void _handleTapUp(TapUpDetails details) { setState(() => _pressed = false); widget.worker.stop(); } void _handleTapCancel() { setState(() => _pressed = false); widget.worker.stop(); } Widget _buildButton(bool hover) { return CustomPaint( size: const Size.fromWidth(11), painter: _SpinnerButtonPainter( direction: widget.direction, isHover: hover, isPressed: _pressed, isEnabled: widget.isEnabled, ), ); } @override Widget build(BuildContext context) { if (!widget.isEnabled) { return _buildButton(false); } return GestureDetector( onTapDown: _handleTapDown, onTapUp: _handleTapUp, onTapCancel: _handleTapCancel, child: HoverBuilder( builder: (BuildContext context, bool hover) { return _buildButton(hover); }, ), ); } } class _SpinnerButtonPainter extends CustomPainter { const _SpinnerButtonPainter({ required this.direction, required this.isHover, required this.isPressed, required this.isEnabled, }); final int direction; final bool isHover; final bool isPressed; final bool isEnabled; @override void paint(ui.Canvas canvas, ui.Size size) { // Paint the background. if (isPressed) { ui.Paint paint = ui.Paint()..color = const Color(0x80000000); canvas.drawRect(Offset.zero & size, paint); } else if (isHover) { ui.Paint paint = ui.Paint()..color = const Color(0x40000000); canvas.drawRect(Offset.zero & size, paint); } // Paint the image. canvas.translate((size.width - 5) / 2, (size.height - 5) / 2); if (direction > 0) { ui.Path path = ui.Path() ..moveTo(0, 4) ..lineTo(2.5, 1) ..lineTo(5, 4); ui.Paint paint = ui.Paint() ..color = isEnabled ? const Color(0xff000000) : const Color(0xff999999); canvas.drawPath(path, paint); } else { ui.Path path = ui.Path() ..moveTo(0, 1) ..lineTo(2.5, 4) ..lineTo(5, 1); ui.Paint paint = ui.Paint() ..color = isEnabled ? const Color(0xff000000) : const Color(0xff999999); canvas.drawPath(path, paint); } } @override bool shouldRepaint(_SpinnerButtonPainter oldDelegate) { return oldDelegate.direction != direction || oldDelegate.isHover != isHover || oldDelegate.isPressed != isPressed; } } class _RawSpinner extends RenderObjectWidget { const _RawSpinner({ Key? key, required this.content, required this.upButton, required this.downButton, }) : super(key: key); final Widget content; final Widget upButton; final Widget downButton; @override RenderObjectElement createElement() => _SpinnerElement(this); @override RenderObject createRenderObject(BuildContext context) => _RenderSpinner(); } enum _SpinnerSlot { content, upButton, downButton } class _SpinnerElement extends RenderObjectElement { _SpinnerElement(_RawSpinner widget) : super(widget); Element? _content; Element? _upButton; Element? _downButton; @override _RawSpinner get widget => super.widget as _RawSpinner; @override _RenderSpinner get renderObject => super.renderObject as _RenderSpinner; @override void visitChildren(ElementVisitor visitor) { if (_content != null) visitor(_content!); if (_upButton != null) visitor(_upButton!); if (_downButton != null) visitor(_downButton!); } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _content = updateChild(_content, widget.content, _SpinnerSlot.content); _upButton = updateChild(_upButton, widget.upButton, _SpinnerSlot.upButton); _downButton = updateChild( _downButton, widget.downButton, _SpinnerSlot.downButton, ); } @override void insertRenderObjectChild(RenderBox child, _SpinnerSlot slot) { switch (slot) { case _SpinnerSlot.content: renderObject.content = child; break; case _SpinnerSlot.upButton: renderObject.upButton = child; break; case _SpinnerSlot.downButton: renderObject.downButton = child; break; } } @override void moveRenderObjectChild( RenderObject _, _SpinnerSlot? __, _SpinnerSlot? ___, ) { assert(false); } @override void update(RenderObjectWidget newWidget) { super.update(newWidget); _content = updateChild(_content, widget.content, _SpinnerSlot.content); _upButton = updateChild(_upButton, widget.upButton, _SpinnerSlot.upButton); _downButton = updateChild( _downButton, widget.downButton, _SpinnerSlot.downButton, ); } @override void forgetChild(Element child) { assert(child == _content || child == _upButton); if (child == _content) { _content = null; } else if (child == _upButton) { _upButton = null; } else if (child == _downButton) { _downButton = null; } super.forgetChild(child); } @override void removeRenderObjectChild(RenderBox child, _SpinnerSlot? slot) { assert( child == renderObject.content || child == renderObject.upButton || child == renderObject.downButton, ); switch (slot) { case _SpinnerSlot.content: renderObject.content = null; break; case _SpinnerSlot.upButton: renderObject.upButton = null; break; case _SpinnerSlot.downButton: renderObject.downButton = null; break; case null: assert(false); } } } class _RenderSpinner extends RenderBox { static const Color baseColor = Color(0xffdddcd5); static final Color bevelColor = brighten(baseColor); RenderBox? _content; RenderBox? get content => _content; set content(RenderBox? value) { if (value == _content) return; if (_content != null) dropChild(_content!); _content = value; if (_content != null) adoptChild(_content!); } RenderBox? _upButton; RenderBox? get upButton => _upButton; set upButton(RenderBox? value) { if (value == _upButton) return; if (_upButton != null) dropChild(_upButton!); _upButton = value; if (_upButton != null) adoptChild(_upButton!); } RenderBox? _downButton; RenderBox? get downButton => _downButton; set downButton(RenderBox? value) { if (value == _downButton) return; if (_downButton != null) dropChild(_downButton!); _downButton = value; if (_downButton != null) adoptChild(_downButton!); } @override void attach(PipelineOwner owner) { super.attach(owner); if (content != null) content!.attach(owner); if (upButton != null) upButton!.attach(owner); if (downButton != null) downButton!.attach(owner); } @override void detach() { super.detach(); if (content != null) content!.detach(); if (upButton != null) upButton!.detach(); if (downButton != null) downButton!.detach(); } @override void visitChildren(RenderObjectVisitor visitor) { if (content != null) visitor(content!); if (upButton != null) visitor(upButton!); if (downButton != null) visitor(downButton!); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { for (RenderBox? child in [downButton, upButton, content]) { if (child != null) { final BoxParentData parentData = child.parentData as BoxParentData; final bool isHit = result.addWithPaintOffset( offset: parentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - parentData.offset); return child.hitTest(result, position: transformed); }, ); if (isHit) { return true; } } } return false; } @override double computeMinIntrinsicWidth(double height) => computeMaxIntrinsicWidth(height); /// Intrinsic width is the sum of our maximum button width plus the content /// width, plus the border. @override double computeMaxIntrinsicWidth(double height) { // Border thickness (left, right, and in between the content & the buttons) double width = 3; final double buttonHeightConstraint = (height - 3) / 2; width += math.max( upButton!.getMaxIntrinsicWidth(buttonHeightConstraint), downButton!.getMaxIntrinsicWidth(buttonHeightConstraint), ); final double contentHeightConstraint = math.max(height - 2, 0); width += content!.getMaxIntrinsicWidth(contentHeightConstraint); return width; } @override double computeMinIntrinsicHeight(double width) => computeMaxIntrinsicHeight(width); /// Intrinsic height is the maximum of the button height and the /// builder's intrinsic height (plus the border), where button height is /// defined as the larger of the two buttons' intrinsic height, doubled. @override double computeMaxIntrinsicHeight(double width) { final double upButtonHeight = upButton!.getMaxIntrinsicHeight( double.infinity, ); final double downButtonHeight = downButton!.getMaxIntrinsicHeight( double.infinity, ); final double height = math.max(upButtonHeight, downButtonHeight) * 2; if (width.isFinite) { // Subtract the button and border width from width constraint. double buttonWidth = math.max( upButton!.getMaxIntrinsicWidth(double.infinity), downButton!.getMaxIntrinsicWidth(double.infinity), ); width = math.max(width - buttonWidth - 2, 0); } return math.max(height, content!.getMaxIntrinsicHeight(width)) + 1; } @override double? computeDistanceToActualBaseline(ui.TextBaseline baseline) { super.computeDistanceToActualBaseline(baseline); double? result = content!.getDistanceToActualBaseline(baseline); if (result != null) { result += 1; } return result; } @override void performLayout() { final double buttonWidth = math.min( upButton!.getMaxIntrinsicWidth(double.infinity), math.max(constraints.maxWidth - 3, 0), ); final BoxConstraints contentConstraints = constraints.deflate( EdgeInsets.only(left: buttonWidth + 3, top: 2), ); content!.layout(contentConstraints, parentUsesSize: true); BoxParentData contentParentData = content!.parentData as BoxParentData; contentParentData.offset = Offset(1, 1); final double buttonHeight = (content!.size.height - 1) / 2; BoxConstraints buttonConstraints = BoxConstraints.tightFor( width: buttonWidth, height: buttonHeight, ); upButton!.layout(buttonConstraints); downButton!.layout(buttonConstraints); size = constraints.constrain( Size(content!.size.width + buttonWidth + 3, content!.size.height + 2), ); BoxParentData upButtonParentData = upButton!.parentData as BoxParentData; upButtonParentData.offset = Offset(size.width - buttonWidth - 1, 1); BoxParentData downButtonParentData = downButton!.parentData as BoxParentData; downButtonParentData.offset = Offset( size.width - buttonWidth - 1, buttonHeight + 2, ); } @override void paint(PaintingContext context, Offset offset) { assert(content != null); assert(upButton != null); assert(downButton != null); BoxParentData contentParentData = content!.parentData as BoxParentData; BoxParentData upButtonParentData = upButton!.parentData as BoxParentData; BoxParentData downButtonParentData = downButton!.parentData as BoxParentData; final double buttonWidth = upButton!.size.width; final double buttonHeight = upButton!.size.height; final Offset upButtonOffset = offset + upButtonParentData.offset; ui.Paint bgPaint = ui.Paint() ..shader = ui.Gradient.linear( upButton!.size.topCenter(upButtonOffset), upButton!.size.bottomCenter(upButtonOffset), <Color>[bevelColor, baseColor], ); final Rect bgRect = Rect.fromLTWH( offset.dx + upButtonParentData.offset.dx, offset.dy, buttonWidth, size.height, ); context.canvas.drawRect(bgRect, bgPaint); context.paintChild(content!, offset + contentParentData.offset); context.paintChild(upButton!, upButtonOffset); context.paintChild(downButton!, offset + downButtonParentData.offset); ui.Paint paint = ui.Paint() ..style = ui.PaintingStyle.stroke ..strokeWidth = 1 ..color = const Color(0xff999999); context.canvas.drawRect( Rect.fromLTWH(0.5, 0.5, size.width - 1, size.height - 1).shift(offset), paint, ); context.canvas.drawLine( offset + Offset(size.width - buttonWidth - 1.5, 0.5), offset + Offset(size.width - buttonWidth - 1.5, size.height - 1), paint, ); context.canvas.drawLine( offset + Offset(size.width - buttonWidth - 1.5, buttonHeight + 1.5), offset + Offset(size.width - 1, buttonHeight + 1.5), paint, ); } @override void redepthChildren() { if (content != null) redepthChild(content!); if (upButton != null) redepthChild(upButton!); if (downButton != null) redepthChild(downButton!); } @override List<DiagnosticsNode> debugDescribeChildren() { return <DiagnosticsNode>[ if (content != null) content!.toDiagnosticsNode(name: 'content'), if (upButton != null) upButton!.toDiagnosticsNode(name: 'upButton'), if (downButton != null) downButton!.toDiagnosticsNode(name: 'downButton'), ]; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/split_pane.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'dart:ui' as ui; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; enum SplitPaneResizePolicy { maintainSplitRatio, maintainBeforeSplitSize, maintainAfterSplitSize, } class SplitPane extends StatelessWidget { const SplitPane({ Key? key, this.orientation = Axis.horizontal, this.initialSplitRatio = 0.5, this.splitterThickness = 6, this.roundToWholePixel = false, this.resizePolicy = SplitPaneResizePolicy.maintainSplitRatio, required this.before, required this.after, }) : super(key: key); final Axis orientation; final double initialSplitRatio; final double splitterThickness; final bool roundToWholePixel; final SplitPaneResizePolicy resizePolicy; final Widget before; final Widget after; @override Widget build(BuildContext context) { return _RawSplitPane( orientation: orientation, initialSplitRatio: initialSplitRatio, splitterThickness: splitterThickness, roundToWholePixel: roundToWholePixel, resizePolicy: resizePolicy, before: before, after: after, splitter: _Splitter(orientation: orientation), ); } } class _Splitter extends StatelessWidget { const _Splitter({Key? key, required this.orientation}) : super(key: key); final Axis orientation; MouseCursor _cursorForOrientation() { switch (orientation) { case Axis.horizontal: return SystemMouseCursors.resizeLeftRight; case Axis.vertical: return SystemMouseCursors.resizeUpDown; } } GestureDragUpdateCallback _handleDrag(BuildContext context) { return (DragUpdateDetails details) { final _RenderSplitPane renderObject = context.findAncestorRenderObjectOfType<_RenderSplitPane>()!; renderObject._handleDrag(details); }; } @override Widget build(BuildContext context) { final GestureDragUpdateCallback handleDrag = _handleDrag(context); return MouseRegion( cursor: _cursorForOrientation(), child: GestureDetector( dragStartBehavior: DragStartBehavior.down, onHorizontalDragUpdate: orientation == Axis.horizontal ? handleDrag : null, onVerticalDragUpdate: orientation == Axis.vertical ? handleDrag : null, child: CustomPaint(painter: _SplitterPainter(orientation)), ), ); } } class _SplitterPainter extends CustomPainter { const _SplitterPainter(this.orientation); final Axis orientation; @override void paint(Canvas canvas, Size size) { late final double imageWidth, imageHeight; switch (orientation) { case Axis.horizontal: imageWidth = size.width - 4; imageHeight = math.min(size.height - 4, 8); break; case Axis.vertical: imageWidth = math.min(size.width - 4, 8); imageHeight = size.height - 4; break; } if (imageWidth > 0 && imageHeight > 0) { double translateX = (size.width - imageWidth) / 2; double translateY = (size.height - imageHeight) / 2; canvas.translate(translateX, translateY); Color dark = const Color(0xffc4c4bc); Color light = const Color(0xffdddcd5); ui.Paint paint = ui.Paint(); switch (orientation) { case Axis.horizontal: paint ..style = PaintingStyle.stroke ..strokeWidth = 1; paint.color = dark; canvas.drawLine(Offset(0, 0.5), Offset(imageWidth, 0.5), paint); canvas.drawLine(Offset(0, 3.5), Offset(imageWidth, 3.5), paint); canvas.drawLine(Offset(0, 6.5), Offset(imageWidth, 6.5), paint); paint.color = light; canvas.drawLine(Offset(0, 1.5), Offset(imageWidth, 1.5), paint); canvas.drawLine(Offset(0, 4.5), Offset(imageWidth, 4.5), paint); canvas.drawLine(Offset(0, 7.5), Offset(imageWidth, 7.5), paint); break; case Axis.vertical: paint..style = PaintingStyle.fill; final double half = imageHeight / 2; paint.color = dark; canvas.drawRect(ui.Rect.fromLTWH(0, 0, 2, half), paint); canvas.drawRect(ui.Rect.fromLTWH(3, 0, 2, half), paint); canvas.drawRect(ui.Rect.fromLTWH(6, 0, 2, half), paint); paint.color = light; canvas.drawRect(ui.Rect.fromLTWH(0, half, 2, half), paint); canvas.drawRect(ui.Rect.fromLTWH(3, half, 2, half), paint); canvas.drawRect(ui.Rect.fromLTWH(6, half, 2, half), paint); break; } } } @override bool shouldRepaint(_SplitterPainter oldDelegate) { return orientation != oldDelegate.orientation; } } class _RawSplitPane extends RenderObjectWidget { const _RawSplitPane({ Key? key, this.orientation = Axis.horizontal, required this.initialSplitRatio, required this.splitterThickness, required this.roundToWholePixel, required this.resizePolicy, required this.before, required this.after, required this.splitter, }) : super(key: key); final Axis orientation; final double initialSplitRatio; final double splitterThickness; final bool roundToWholePixel; final SplitPaneResizePolicy resizePolicy; final Widget before; final Widget after; final Widget splitter; @override RenderObjectElement createElement() => _SplitPaneElement(this); @override RenderObject createRenderObject(BuildContext context) { return _RenderSplitPane( orientation: orientation, splitRatio: initialSplitRatio, splitterThickness: splitterThickness, roundToWholePixel: roundToWholePixel, resizePolicy: resizePolicy, ); } @override void updateRenderObject(BuildContext context, _RenderSplitPane renderObject) { renderObject ..orientation = orientation ..splitterThickness = splitterThickness ..roundToWholePixel = roundToWholePixel ..resizePolicy = resizePolicy; } } enum _SplitPaneSlot { before, after, splitter } class _SplitPaneElement extends RenderObjectElement { _SplitPaneElement(_RawSplitPane widget) : super(widget); Element? _before; Element? _after; Element? _splitter; @override _RawSplitPane get widget => super.widget as _RawSplitPane; @override _RenderSplitPane get renderObject => super.renderObject as _RenderSplitPane; @override void visitChildren(ElementVisitor visitor) { if (_before != null) visitor(_before!); if (_after != null) visitor(_after!); if (_splitter != null) visitor(_splitter!); } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); _before = updateChild(_before, widget.before, _SplitPaneSlot.before); _after = updateChild(_after, widget.after, _SplitPaneSlot.after); _splitter = updateChild( _splitter, widget.splitter, _SplitPaneSlot.splitter, ); } @override void insertRenderObjectChild(RenderBox child, _SplitPaneSlot slot) { switch (slot) { case _SplitPaneSlot.before: renderObject.before = child; break; case _SplitPaneSlot.after: renderObject.after = child; break; case _SplitPaneSlot.splitter: renderObject.splitter = child; break; } } @override void moveRenderObjectChild( RenderObject _, _SplitPaneSlot? __, _SplitPaneSlot? ___, ) { assert(false); } @override void update(RenderObjectWidget newWidget) { super.update(newWidget); _before = updateChild(_before, widget.before, _SplitPaneSlot.before); _after = updateChild(_after, widget.after, _SplitPaneSlot.after); _splitter = updateChild( _splitter, widget.splitter, _SplitPaneSlot.splitter, ); } @override void forgetChild(Element child) { assert(child == _before || child == _after); if (child == _before) { _before = null; } else if (child == _after) { _after = null; } else if (child == _splitter) { _splitter = null; } super.forgetChild(child); } @override void removeRenderObjectChild(RenderBox child, _SplitPaneSlot? slot) { assert( child == renderObject.before || child == renderObject.after || child == renderObject.splitter, ); switch (slot) { case _SplitPaneSlot.before: renderObject.before = null; break; case _SplitPaneSlot.after: renderObject.after = null; break; case _SplitPaneSlot.splitter: renderObject.splitter = null; break; case null: assert(false); } } } class _RenderSplitPane extends RenderBox { _RenderSplitPane({ Axis orientation = Axis.horizontal, double splitRatio = 0.5, double splitterThickness = 6, bool roundToWholePixel = false, SplitPaneResizePolicy resizePolicy = SplitPaneResizePolicy.maintainSplitRatio, }) { this.orientation = orientation; this.splitRatio = splitRatio; this.splitterThickness = splitterThickness; this.roundToWholePixel = roundToWholePixel; this.resizePolicy = resizePolicy; } Axis? _orientation; Axis get orientation => _orientation!; set orientation(Axis value) { if (value == _orientation) return; _orientation = value; markNeedsLayout(); } double? _splitRatio; double get splitRatio => _splitRatio!; set splitRatio(double value) { assert(value >= 0 && value <= 1); if (value == _splitRatio) return; _splitRatio = value; markNeedsLayout(); } double? _splitterThickness; double get splitterThickness => _splitterThickness!; set splitterThickness(double value) { assert(value > 0); if (value == _splitterThickness) return; _splitterThickness = value; markNeedsLayout(); } bool? _roundToWholePixel; bool get roundToWholePixel => _roundToWholePixel!; set roundToWholePixel(bool value) { if (value == _roundToWholePixel) return; _roundToWholePixel = value; markNeedsLayout(); } SplitPaneResizePolicy? _resizePolicy; SplitPaneResizePolicy get resizePolicy => _resizePolicy!; set resizePolicy(SplitPaneResizePolicy value) { if (value == _resizePolicy) return; _resizePolicy = value; } RenderBox? _before; RenderBox? get before => _before; set before(RenderBox? value) { if (value == _before) return; if (_before != null) dropChild(_before!); _before = value; if (_before != null) adoptChild(_before!); } RenderBox? _after; RenderBox? get after => _after; set after(RenderBox? value) { if (value == _after) return; if (_after != null) dropChild(_after!); _after = value; if (_after != null) adoptChild(_after!); } RenderBox? _splitter; RenderBox? get splitter => _splitter; set splitter(RenderBox? value) { if (value == _splitter) return; if (_splitter != null) dropChild(_splitter!); _splitter = value; if (_splitter != null) adoptChild(_splitter!); } double _constrainSplitX(double splitX) { return math.max(math.min(splitX, size.width - splitterThickness), 0); } double _constrainSplitY(double splitY) { return math.max(math.min(splitY, size.height - splitterThickness), 0); } void _handleDrag(DragUpdateDetails details) { late final double newSplitRatio; switch (orientation) { case Axis.horizontal: final double oldSplitX = splitRatio * size.width; final double newSplitX = _constrainSplitX(oldSplitX + details.delta.dx); newSplitRatio = newSplitX / size.width; break; case Axis.vertical: final double oldSplitY = splitRatio * size.height; final double newSplitY = _constrainSplitY(oldSplitY + details.delta.dy); newSplitRatio = newSplitY / size.height; break; } splitRatio = newSplitRatio; } @override void attach(PipelineOwner owner) { super.attach(owner); if (before != null) before!.attach(owner); if (after != null) after!.attach(owner); if (splitter != null) splitter!.attach(owner); } @override void detach() { super.detach(); if (before != null) before!.detach(); if (after != null) after!.detach(); if (splitter != null) splitter!.detach(); } @override void visitChildren(RenderObjectVisitor visitor) { if (before != null) visitor(before!); if (after != null) visitor(after!); if (splitter != null) visitor(splitter!); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { for (RenderBox? child in [splitter, after, before]) { if (child != null) { final BoxParentData parentData = child.parentData as BoxParentData; final bool isHit = result.addWithPaintOffset( offset: parentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - parentData.offset); return child.hitTest(result, position: transformed); }, ); if (isHit) { return true; } } } return false; } @override double computeMinIntrinsicWidth(double height) => 0; @override double computeMaxIntrinsicWidth(double height) => computeMinIntrinsicWidth(height); @override double computeMinIntrinsicHeight(double width) => 0; @override double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); @override void performLayout() { switch (orientation) { case Axis.horizontal: assert(constraints.hasTightWidth); assert(constraints.hasBoundedHeight); final double? previousWidth = hasSize ? size.width : null; size = constraints.biggest; late double splitX; if (previousWidth == null || previousWidth == size.width) { splitX = size.width * splitRatio; } else { switch (resizePolicy) { case SplitPaneResizePolicy.maintainSplitRatio: splitX = _constrainSplitX(size.width * splitRatio); break; case SplitPaneResizePolicy.maintainBeforeSplitSize: final double oldSplitX = previousWidth * splitRatio; splitX = _constrainSplitX(oldSplitX); _splitRatio = splitX / size.width; break; case SplitPaneResizePolicy.maintainAfterSplitSize: final double oldSplitX = previousWidth * splitRatio; final double deltaWidth = size.width - previousWidth; splitX = _constrainSplitX(oldSplitX + deltaWidth); _splitRatio = splitX / size.width; break; } } if (roundToWholePixel) { splitX = splitX.roundToDouble(); } final BoxConstraints beforeConstraints = BoxConstraints.tightFor( width: splitX, height: size.height, ); before!.layout(beforeConstraints); double splitterThickness = this.splitterThickness; if (roundToWholePixel) { splitterThickness = splitterThickness.roundToDouble(); } splitter!.layout( BoxConstraints.tightFor( width: splitterThickness, height: size.height, ), ); BoxParentData splitterParentData = splitter!.parentData as BoxParentData; splitterParentData.offset = Offset(splitX, 0); final double afterX = splitX + splitterThickness; final BoxConstraints afterConstraints = BoxConstraints.tightFor( width: size.width - afterX, height: size.height, ); after!.layout(afterConstraints); BoxParentData afterParentData = after!.parentData as BoxParentData; afterParentData.offset = Offset(afterX, 0); break; case Axis.vertical: assert(constraints.hasTightHeight); assert(constraints.hasBoundedWidth); final double? previousHeight = hasSize ? size.height : null; size = constraints.biggest; late double splitY; if (previousHeight == null || previousHeight == size.height) { splitY = size.height * splitRatio; } else { switch (resizePolicy) { case SplitPaneResizePolicy.maintainSplitRatio: splitY = _constrainSplitY(size.height * splitRatio); break; case SplitPaneResizePolicy.maintainBeforeSplitSize: final double oldSplitY = previousHeight * splitRatio; splitY = _constrainSplitY(oldSplitY); _splitRatio = splitY / size.height; break; case SplitPaneResizePolicy.maintainAfterSplitSize: final double oldSplitY = previousHeight * splitRatio; final double deltaHeight = size.height - previousHeight; splitY = _constrainSplitY(oldSplitY + deltaHeight); _splitRatio = splitY / size.height; break; } } if (roundToWholePixel) { splitY = splitY.roundToDouble(); } final BoxConstraints beforeConstraints = BoxConstraints.tightFor( width: size.width, height: splitY, ); before!.layout(beforeConstraints); double splitterThickness = this.splitterThickness; if (roundToWholePixel) { splitterThickness = splitterThickness.roundToDouble(); } splitter!.layout( BoxConstraints.tightFor(width: size.width, height: splitterThickness), ); BoxParentData splitterParentData = splitter!.parentData as BoxParentData; splitterParentData.offset = Offset(0, splitY); final double afterY = splitY + splitterThickness; final BoxConstraints afterConstraints = BoxConstraints.tightFor( width: size.width, height: size.height - afterY, ); after!.layout(afterConstraints); BoxParentData afterParentData = after!.parentData as BoxParentData; afterParentData.offset = Offset(0, afterY); break; } } @override void paint(PaintingContext context, Offset offset) { assert(before != null); assert(after != null); context.paintChild(before!, offset); BoxParentData afterParentData = after!.parentData as BoxParentData; context.paintChild(after!, offset + afterParentData.offset); BoxParentData splitterParentData = splitter!.parentData as BoxParentData; context.paintChild(splitter!, offset + splitterParentData.offset); } @override void redepthChildren() { if (before != null) redepthChild(before!); if (after != null) redepthChild(after!); if (splitter != null) redepthChild(splitter!); } @override List<DiagnosticsNode> debugDescribeChildren() { return <DiagnosticsNode>[ if (before != null) before!.toDiagnosticsNode(name: 'before'), if (after != null) after!.toDiagnosticsNode(name: 'after'), if (splitter != null) splitter!.toDiagnosticsNode(name: 'splitter'), ]; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/tab_pane.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/widgets.dart'; class Tab { const Tab({required this.label, required this.builder}); final String label; final WidgetBuilder builder; } class TabPane extends StatefulWidget { const TabPane({Key? key, this.initialSelectedIndex = 0, required this.tabs}) : super(key: key); final int initialSelectedIndex; final List<Tab> tabs; @override _TabPaneState createState() => _TabPaneState(); } class _TabPaneState extends State<TabPane> { late int selectedIndex; @override void initState() { super.initState(); selectedIndex = widget.initialSelectedIndex; } @override Widget build(BuildContext context) { final List<Widget> tabs = <Widget>[]; for (int i = 0; i < widget.tabs.length; i++) { final Tab tab = widget.tabs[i]; if (i == selectedIndex) { tabs.add( DecoratedBox( decoration: const BoxDecoration( color: Color(0xfff7f5ee), border: Border( top: BorderSide(width: 1, color: Color(0xff999999)), bottom: BorderSide(width: 1, color: Color(0xfff7f5ee)), left: BorderSide(width: 1, color: Color(0xff999999)), right: BorderSide(width: 1, color: Color(0xff999999)), ), gradient: LinearGradient( begin: Alignment(0, -0.85), end: Alignment(0, -0.65), colors: <Color>[Color(0xffe2e0d8), Color(0xfff7f5ee)], ), ), child: Padding( padding: const EdgeInsets.fromLTRB(4, 3, 4, 4), child: Text(tab.label), ), ), ); } else { tabs.add( MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { setState(() { selectedIndex = i; }); }, child: DecoratedBox( decoration: const BoxDecoration( color: Color(0xffc4c3bc), border: Border( top: BorderSide(width: 1, color: Color(0xff999999)), bottom: BorderSide(width: 1, color: Color(0xff999999)), left: BorderSide(width: 1, color: Color(0xff999999)), right: BorderSide(width: 1, color: Color(0xff999999)), ), gradient: LinearGradient( begin: Alignment(0, -0.85), end: Alignment(0, -0.65), colors: <Color>[Color(0xffdad8d0), Color(0xffc4c3bc)], ), ), child: Padding( padding: const EdgeInsets.fromLTRB(4, 3, 4, 4), child: Text(tab.label), ), ), ), ), ); } tabs.add( DecoratedBox( decoration: const BoxDecoration( border: Border( bottom: BorderSide(width: 1, color: Color(0xff999999)), ), ), child: const SizedBox(width: 2), ), ); } tabs.add( Expanded( child: DecoratedBox( decoration: const BoxDecoration( border: Border( bottom: BorderSide(width: 1, color: Color(0xff999999)), ), ), child: const SizedBox(width: 4), ), ), ); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row(crossAxisAlignment: CrossAxisAlignment.end, children: tabs), Expanded( child: DecoratedBox( decoration: const BoxDecoration( border: Border( left: BorderSide(width: 1, color: Color(0xff999999)), right: BorderSide(width: 1, color: Color(0xff999999)), bottom: BorderSide(width: 1, color: Color(0xff999999)), ), color: const Color(0xfff7f5ee), ), child: widget.tabs[selectedIndex].builder(context), ), ), ], ); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/table_pane.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:math' as math; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'foundation.dart'; import 'indexed_offset.dart'; void main() { runApp( ColoredBox( color: const Color(0xffffffff), child: Directionality( textDirection: TextDirection.ltr, child: DefaultTextStyle( style: TextStyle( fontFamily: 'Verdana', color: const Color(0xff000000), ), child: TablePane( verticalIntrinsicSize: MainAxisSize.min, horizontalSpacing: 5, verticalSpacing: 20, columns: <TablePaneColumn>[ TablePaneColumn(width: RelativeTablePaneColumnWidth(weight: 2)), TablePaneColumn(width: RelativeTablePaneColumnWidth(weight: 20)), TablePaneColumn(width: RelativeTablePaneColumnWidth(weight: 1)), TablePaneColumn(width: RelativeTablePaneColumnWidth(weight: 3)), TablePaneColumn(width: RelativeTablePaneColumnWidth(weight: 1)), TablePaneColumn(width: RelativeTablePaneColumnWidth(weight: 1)), ], children: <Widget>[ TableRow( height: RelativeTablePaneRowHeight(weight: 5), children: [ ColoredCell(), ColoredCell(), ColoredCell(), ColoredCell(), ColoredCell(), ColoredCell(), ], ), TableRow( children: [ ColoredCell(), TableCell(rowSpan: 2, child: ColoredCell(text: 'rowSpan=2')), ColoredCell(), ColoredCell(), ColoredCell(), ColoredCell(), ], ), TableRow( children: [ ColoredCell(), EmptyTableCell(), ColoredCell(), TableCell( columnSpan: 2, child: ColoredCell(text: 'columnSpan=2'), ), EmptyTableCell(), ColoredCell(), ], ), TableRow( children: [ ColoredCell(), ColoredCell(), TableCell( rowSpan: 3, columnSpan: 3, child: ColoredCell(text: 'rowSpan=3\ncolumnSpan=3'), ), EmptyTableCell(), EmptyTableCell(), ColoredCell(), ], ), TableRow( children: [ ColoredCell(), ColoredCell(), EmptyTableCell(), EmptyTableCell(), EmptyTableCell(), ColoredCell(), ], ), TableRow( children: [ ColoredCell(), ColoredCell(), EmptyTableCell(), EmptyTableCell(), EmptyTableCell(), ColoredCell(), ], ), ], ), ), ), ), ); } class ColoredCell extends StatelessWidget { const ColoredCell({this.text = 'cell'}); final String text; @override Widget build(BuildContext context) { final math.Random random = math.Random(); return ColoredBox( color: Color(0xff000000 | random.nextInt(math.pow(256, 3) as int)), child: Align(child: Text(text)), ); } } typedef _IntrinsicComputer = double Function(RenderBox child, double crossAxisConstraint); double _sum(double a, double b) => a + b; class TablePaneColumn with Diagnosticable { const TablePaneColumn({this.width = const RelativeTablePaneColumnWidth()}); final TablePaneColumnWidth width; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<TablePaneColumnWidth>('width', width)); } } abstract class TablePaneColumnWidth with Diagnosticable { const TablePaneColumnWidth._(); @protected double get width; @protected bool get isRelative; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('width', width)); properties.add(DiagnosticsProperty<bool>('isRelative', isRelative)); } } class IntrinsicTablePaneColumnWidth extends TablePaneColumnWidth { const IntrinsicTablePaneColumnWidth([this.mainAxisSize = MainAxisSize.max]) : super._(); final MainAxisSize mainAxisSize; @override @protected double get width => -1; @override @protected bool get isRelative => false; } class FixedTablePaneColumnWidth extends TablePaneColumnWidth { const FixedTablePaneColumnWidth(this.width) : assert(width >= 0), super._(); @override @protected final double width; @override @protected bool get isRelative => false; } class RelativeTablePaneColumnWidth extends TablePaneColumnWidth { const RelativeTablePaneColumnWidth({this.weight = 1}) : super._(); final double weight; @override @protected double get width => weight; @override @protected bool get isRelative => true; } abstract class TablePaneRowHeight { const TablePaneRowHeight._(); @protected double get height; @protected bool get isRelative; } class IntrinsicTablePaneRowHeight extends TablePaneRowHeight { const IntrinsicTablePaneRowHeight([this.mainAxisSize = MainAxisSize.max]) : super._(); final MainAxisSize mainAxisSize; @override @protected double get height => -1; @override @protected bool get isRelative => false; } class FixedTablePaneRowHeight extends TablePaneRowHeight { const FixedTablePaneRowHeight(this.height) : assert(height >= 0), super._(); @override @protected final double height; @override @protected bool get isRelative => false; } class RelativeTablePaneRowHeight extends TablePaneRowHeight { const RelativeTablePaneRowHeight({this.weight = 1}) : super._(); final double weight; @override @protected double get height => weight; @override @protected bool get isRelative => true; } class TableCell extends ParentDataWidget<TableCellParentData> { /// Creates a widget that controls the row-span and column-span of a child of /// [TablePane]. const TableCell({ Key? key, this.rowSpan = 1, this.columnSpan = 1, required Widget child, }) : assert(rowSpan > 0), assert(columnSpan > 0), super(key: key, child: child); /// The number of rows this cell occupies. final int rowSpan; /// The number of columns this cell occupies. final int columnSpan; @override void applyParentData(RenderObject renderObject) { final TableCellParentData parentData = renderObject.parentData as TableCellParentData; if (parentData.rowSpan != rowSpan || parentData.columnSpan != columnSpan) { parentData.rowSpan = rowSpan; parentData.columnSpan = columnSpan; RenderObject? targetParent = renderObject.parent; while (targetParent != null && targetParent is! RenderTablePane) { targetParent = targetParent.parent; } if (targetParent is RenderTablePane) { targetParent.markNeedsMetrics(); } } } @override Type get debugTypicalAncestorWidgetClass => TableRow; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('rowSpan', rowSpan)); properties.add(IntProperty('columnSpan', columnSpan)); } } class EmptyTableCell extends LeafRenderObjectWidget { const EmptyTableCell({Key? key}) : super(key: key); @override RenderObject createRenderObject(BuildContext context) => RenderEmptyTableCell(); } /// TablePane's layout is "width in, height out", meaning it will compute its /// column widths first with unconstrained height, then compute the row heights /// using those column widths as the width constraints. class TablePane extends MultiChildRenderObjectWidget { TablePane({ Key? key, required this.columns, this.horizontalSpacing = 0, this.verticalSpacing = 0, this.horizontalIntrinsicSize = MainAxisSize.max, this.horizontalRelativeSize = MainAxisSize.max, this.verticalIntrinsicSize = MainAxisSize.max, this.verticalRelativeSize = MainAxisSize.max, this.metricsController, required List<Widget> children, }) : super(key: key, children: children); final List<TablePaneColumn> columns; final double horizontalSpacing; final double verticalSpacing; final MainAxisSize horizontalIntrinsicSize; final MainAxisSize horizontalRelativeSize; final MainAxisSize verticalIntrinsicSize; final MainAxisSize verticalRelativeSize; final TablePaneMetricsController? metricsController; @override List<Widget> get children => super.children; @override TablePaneElement createElement() => TablePaneElement(this); @override RenderObject createRenderObject(BuildContext context) { return RenderTablePane( columns: columns, horizontalSpacing: horizontalSpacing, verticalSpacing: verticalSpacing, horizontalIntrinsicSize: horizontalIntrinsicSize, horizontalRelativeSize: horizontalRelativeSize, verticalIntrinsicSize: verticalIntrinsicSize, verticalRelativeSize: verticalRelativeSize, metricsController: metricsController, ); } @override void updateRenderObject(BuildContext context, RenderTablePane renderObject) { renderObject ..columns = columns ..horizontalSpacing = horizontalSpacing ..verticalSpacing = verticalSpacing ..horizontalIntrinsicSize = horizontalIntrinsicSize ..horizontalRelativeSize = horizontalRelativeSize ..verticalIntrinsicSize = verticalIntrinsicSize ..verticalRelativeSize = verticalRelativeSize ..metricsController = metricsController; } static int _indexOf(Element child, Element parent) { int i = -1, result = -1; parent.visitChildren((Element element) { i++; if (element == child) { assert(result == -1); result = i; } }); return result; } static IndexedOffset? offsetOf(BuildContext context) { TableRowElement? row; Element? rawCell; context.visitAncestorElements((Element element) { if (element is TableRowElement) { row = element; rawCell ??= context as Element; return false; } rawCell = element; return true; }); if (row != null) { assert(rawCell != null); final int columnIndex = _indexOf(rawCell!, row!); assert(columnIndex >= 0); TablePaneElement? tablePane; Element? rawRow; row!.visitAncestorElements((Element element) { if (element is TablePaneElement) { tablePane = element; rawRow ??= row; return false; } rawRow = element; return true; }); assert(tablePane != null); assert(rawRow != null); final int rowIndex = _indexOf(rawRow!, tablePane!); assert(rowIndex >= 0); return IndexedOffset(rowIndex, columnIndex); } return null; } static TablePaneElement? of(BuildContext context) { if (context is TablePaneElement) { return context; } TablePaneElement? tablePane; context.visitAncestorElements((Element element) { if (element is TablePaneElement) { tablePane = element; return false; } return true; }); return tablePane; } } class TablePaneElement extends MultiChildRenderObjectElement { TablePaneElement(TablePane widget) : super(widget); } class TableRow extends MultiChildRenderObjectWidget { TableRow({ Key? key, this.height = const IntrinsicTablePaneRowHeight(), this.backgroundColor, required List<Widget> children, }) : super(key: key, children: children); final TablePaneRowHeight height; final Color? backgroundColor; @override List<Widget> get children => super.children; @override TableRowElement createElement() => TableRowElement(this); @override RenderObject createRenderObject(BuildContext context) { return RenderTableRow(height: height, backgroundColor: backgroundColor); } @override void updateRenderObject(BuildContext context, RenderTableRow renderObject) { renderObject ..height = height ..backgroundColor = backgroundColor; } } class TableRowElement extends MultiChildRenderObjectElement { TableRowElement(TableRow widget) : super(widget); } /// [ParentData] used by [RenderTablePane]. class TableRowParentData extends ContainerBoxParentData<RenderTableRow> {} /// [ParentData] used by [RenderTableRow]. class TableCellParentData extends ContainerBoxParentData<RenderBox> { /// The column that the child was in the last time it was laid out. int? x; int _rowSpan = 1; int get rowSpan => _rowSpan; set rowSpan(int value) { assert(value > 0); _rowSpan = value; } int _columnSpan = 1; int get columnSpan => _columnSpan; set columnSpan(int value) { assert(value > 0); _columnSpan = value; } @override String toString() => '${super.toString()}; $rowSpan rows x $columnSpan columns'; } class TableRowConstraints extends BoxConstraints { // const TableRowConstraints({ // double minWidth = 0, // double maxWidth = double.infinity, // double minHeight = 0, // double maxHeight = double.infinity, // @required this.cellConstraints, // @required this.cellPositions, // }) : super(minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight); TableRowConstraints.tightFor({ double? width, double? height, required this.cellConstraints, required this.cellPositions, }) : super.tightFor(width: width, height: height); final List<BoxConstraints> cellConstraints; final List<Offset> cellPositions; @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is TableRowConstraints && super == other && const ListEquality().equals(other.cellConstraints, cellConstraints) && const ListEquality().equals(other.cellPositions, cellPositions); } @override int get hashCode { assert(debugAssertIsValid()); return Object.hash( super.hashCode, Object.hashAll(cellConstraints), Object.hashAll(cellPositions), ); } @override String toString() { return 'TableRowConstraints(base=${super.toString()}, ' 'cellConstraints=$cellConstraints), ' 'cellPositions=$cellPositions'; } } class RenderEmptyTableCell extends RenderBox { @override bool get sizedByParent => true; @override Size computeDryLayout(BoxConstraints constraints) { return constraints.smallest; } } mixin ChildListRenderObjectMixin< ChildType extends RenderBox, ParentDataType extends ContainerBoxParentData<ChildType> > on RenderBoxContainerDefaultsMixin<ChildType, ParentDataType> { List<RenderBox>? _children; @protected List<RenderBox> get children { return _children ??= getChildrenAsList(); } @protected @mustCallSuper void markNeedsChildren() { _children = null; } /// The number of children belonging to this render object. int get length => childCount; /// Gets the child at the specified index. RenderBox operator [](int index) => children[index]; @override void insert(RenderBox child, {RenderBox? after}) { super.insert(child as ChildType, after: after as ChildType?); markNeedsChildren(); } @override void remove(RenderBox child) { super.remove(child as ChildType); markNeedsChildren(); } @override void removeAll() { super.removeAll(); markNeedsChildren(); } @override void move(RenderBox child, {RenderBox? after}) { super.move(child as ChildType, after: after as ChildType?); markNeedsChildren(); } } class RenderTableRow extends RenderBox with ContainerRenderObjectMixin<RenderBox, TableCellParentData>, RenderBoxContainerDefaultsMixin<RenderBox, TableCellParentData>, ChildListRenderObjectMixin<RenderBox, TableCellParentData> { RenderTableRow({required TablePaneRowHeight height, Color? backgroundColor}) { this.height = height; this.backgroundColor = backgroundColor; } TablePaneRowHeight _height = const IntrinsicTablePaneRowHeight(); TablePaneRowHeight get height => _height; set height(TablePaneRowHeight value) { if (value != _height) { _height = value; markNeedsLayout(); if (parent != null) { parent!.markNeedsMetrics(); } } } Color? _backgroundColor; Color? get backgroundColor => _backgroundColor; set backgroundColor(Color? value) { if (value != _backgroundColor) { _backgroundColor = value; markNeedsPaint(); } } @override TableRowConstraints get constraints => super.constraints as TableRowConstraints; @override RenderTablePane? get parent => super.parent as RenderTablePane?; @override void setupParentData(RenderBox child) { if (child.parentData is! TableCellParentData) { child.parentData = TableCellParentData(); } } @override @protected void markNeedsChildren() { super.markNeedsChildren(); parent!.markNeedsMetrics(); } @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } @override void markNeedsLayout() { RenderTablePane? parent = this.parent; if (parent != null) { parent.markNeedsMetrics(); markParentNeedsLayout(); return; } super.markNeedsLayout(); } @override void performLayout() { // RenderTablePane will always give us tight constraints assert(constraints.isTight); size = constraints.smallest; for (int i = 0; i < length; i++) { final RenderBox child = this[i]; final BoxParentData childParentData = child.parentData as BoxParentData; child.layout(constraints.cellConstraints[i]); childParentData.offset = constraints.cellPositions[i]; } } @override void paint(PaintingContext context, Offset offset) { if (backgroundColor != null) { final Paint paint = Paint() ..style = PaintingStyle.fill ..color = backgroundColor!; context.canvas.drawRect(offset & size, paint); } defaultPaint(context, offset); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<TablePaneRowHeight>('height', height)); } } class RenderTablePane extends RenderBox with ContainerRenderObjectMixin<RenderTableRow, TableRowParentData>, RenderBoxContainerDefaultsMixin<RenderTableRow, TableRowParentData>, ChildListRenderObjectMixin<RenderTableRow, TableRowParentData> { RenderTablePane({ required List<TablePaneColumn> columns, double horizontalSpacing = 0, double verticalSpacing = 0, MainAxisSize horizontalIntrinsicSize = MainAxisSize.max, MainAxisSize horizontalRelativeSize = MainAxisSize.max, MainAxisSize verticalIntrinsicSize = MainAxisSize.max, MainAxisSize verticalRelativeSize = MainAxisSize.max, TablePaneMetricsController? metricsController, }) { this.columns = columns; this.horizontalSpacing = horizontalSpacing; this.verticalSpacing = verticalSpacing; this.horizontalIntrinsicSize = horizontalIntrinsicSize; this.horizontalRelativeSize = horizontalRelativeSize; this.verticalIntrinsicSize = verticalIntrinsicSize; this.verticalRelativeSize = verticalRelativeSize; this.metricsController = metricsController; } List<TablePaneColumn> _columns = const <TablePaneColumn>[]; List<TablePaneColumn> get columns => _columns; set columns(List<TablePaneColumn> value) { if (!const ListEquality().equals(value, _columns)) { _columns = value; markNeedsMetrics(); } } double _horizontalSpacing = 0; double get horizontalSpacing => _horizontalSpacing; set horizontalSpacing(double value) { if (value != _horizontalSpacing) { _horizontalSpacing = value; markNeedsMetrics(); } } double _verticalSpacing = 0; double get verticalSpacing => _verticalSpacing; set verticalSpacing(double value) { if (value != _verticalSpacing) { _verticalSpacing = value; markNeedsMetrics(); } } MainAxisSize _horizontalIntrinsicSize = MainAxisSize.max; MainAxisSize get horizontalIntrinsicSize => _horizontalIntrinsicSize; set horizontalIntrinsicSize(MainAxisSize value) { if (value != _horizontalIntrinsicSize) { _horizontalIntrinsicSize = value; markNeedsMetrics(); } } MainAxisSize _horizontalRelativeSize = MainAxisSize.max; MainAxisSize get horizontalRelativeSize => _horizontalRelativeSize; set horizontalRelativeSize(MainAxisSize value) { if (value != _horizontalRelativeSize) { _horizontalRelativeSize = value; markNeedsMetrics(); } } MainAxisSize _verticalIntrinsicSize = MainAxisSize.max; MainAxisSize get verticalIntrinsicSize => _verticalIntrinsicSize; set verticalIntrinsicSize(MainAxisSize value) { if (value != _verticalIntrinsicSize) { _verticalIntrinsicSize = value; markNeedsMetrics(); } } MainAxisSize _verticalRelativeSize = MainAxisSize.max; MainAxisSize get verticalRelativeSize => _verticalRelativeSize; set verticalRelativeSize(MainAxisSize value) { if (value != _verticalRelativeSize) { _verticalRelativeSize = value; markNeedsMetrics(); } } TablePaneMetricsController? _metricsController; TablePaneMetricsController? get metricsController => _metricsController; set metricsController(TablePaneMetricsController? value) { if (value != _metricsController) { if (_metricsController != null && attached) { _metricsController!._detach(); } _metricsController = value; if (value != null && attached) { value._attach(this); } } } /// Computes the intrinsic height of a table pane row, which is defined as /// the maximum intrinsic height of the row's cells. /// /// Because their intrinsic height relates to the intrinsic heights of other /// rows, cells that span multiple rows will not be considered in this /// calculation (even if they live in the row directly). It is up to the /// caller to factor such cells into the row heights calculation. double _computeIntrinsicRowHeight( int rowIndex, List<double> columnWidths, _IntrinsicComputer computeIntrinsicCellHeight, ) { assert(rowIndex >= 0 && rowIndex < rows.length); final RenderTableRow row = rows[rowIndex]; double result = 0; for (int j = 0, n = row.length, m = columns.length; j < n && j < m; j++) { final RenderBox child = row[j]; final TableCellParentData childParentData = child.parentData as TableCellParentData; if (childParentData.rowSpan == 1) { result = math.max( result, computeIntrinsicCellHeight(child, columnWidths[j]), ); } } return result; } /// Gets the intrinsic width of a table pane column, which is defined as the /// maximum intrinsic width of the column's cells. /// /// Because their intrinsic width relates to the intrinsic widths of other /// columns, cells that span multiple columns will not be considered in /// this calculation (even if they live in the column directly). It is up to /// the caller to factor such cells into the column widths calculation. double _computeIntrinsicColumnWidth( int columnIndex, _IntrinsicComputer computeIntrinsicCellWidth, ) { double result = 0; for (int i = 0, n = rows.length; i < n; i++) { final RenderTableRow row = rows[i]; if (columnIndex < row.length) { final RenderBox child = row[columnIndex]; final TableCellParentData childParentData = child.parentData as TableCellParentData; if (childParentData.columnSpan == 1) { result = math.max( result, computeIntrinsicCellWidth(child, double.infinity), ); } } } return result; } List<double> _computeIntrinsicRowHeights( double width, _IntrinsicComputer computeIntrinsicCellHeight, ) { assert(!width.isNegative); final List<double> rowHeights = List<double>.filled(rows.length, 0); final List<double> relativeWeights = List<double>.filled(rows.length, 0); final List<bool> intrinsicHeightRows = List<bool>.filled( rows.length, false, ); final List<double> columnWidths = width.isFinite ? _computeActualColumnWidths(LinearConstraints.tight(width)) : _computeIntrinsicColumnWidths(_computeIntrinsicChildWidth); // First, we calculate the base heights of the rows, giving relative // rows their intrinsic height. Spanning cells will be ignored in this // pass. double totalRelativeWeight = 0; for (int i = 0; i < rows.length; i++) { final TablePaneRowHeight heightSpec = rows[i].height; final double rowHeight = heightSpec.height; final bool isRelative = heightSpec.isRelative; final bool isIntrinsic = intrinsicHeightRows[i] = rowHeight < 0; if (isRelative) { relativeWeights[i] = rowHeight; totalRelativeWeight += rowHeight; } if (isIntrinsic || isRelative) { rowHeights[i] = _computeIntrinsicRowHeight( i, columnWidths, computeIntrinsicCellHeight, ); } else { rowHeights[i] = rowHeight; } } // Next, we account for spanning cells, which have been ignored thus // far. If any spanned cell is intrinsic-height (including relative height // rows), then we ensure that the sum of the heights of the spanned cells // is enough to satisfy the intrinsic height of the spanning content. for (int i = 0; i < rows.length; i++) { final RenderTableRow row = rows[i]; for (int j = 0, n = row.length, m = columns.length; j < n && j < m; j++) { final RenderBox child = row[j]; if (child is! RenderEmptyTableCell) { final TableCellParentData childParentData = child.parentData as TableCellParentData; final int rowSpan = childParentData.rowSpan; if (rowSpan > 1) { // We might need to adjust row heights to accommodate this spanning // cell. First, we find out if any of the spanned cells are // intrinsic height or relative height and how much space we've // allocated thus far for those cells. int spannedIntrinsicHeightCellCount = 0; double spannedRelativeWeight = 0; double spannedHeight = 0; for (int k = 0; k < rowSpan && i + k < rows.length; k++) { spannedRelativeWeight += relativeWeights[i + k]; spannedHeight += rowHeights[i + k]; if (intrinsicHeightRows[i + k]) { spannedIntrinsicHeightCellCount++; } } if (spannedRelativeWeight > 0 || spannedIntrinsicHeightCellCount > 0) { final int columnSpan = childParentData.columnSpan; double childWidth = columnWidths .skip(j) .take(columnSpan) .fold<double>(0, _sum); childWidth += math.max(columnSpan - 1, 0) * horizontalSpacing; final double childIntrinsicHeight = computeIntrinsicCellHeight( child, childWidth, ); if (childIntrinsicHeight > spannedHeight) { // The child's intrinsic height is larger than the height we've // allocated thus far, so an adjustment is necessary. final double adjustment = childIntrinsicHeight - spannedHeight; if (spannedRelativeWeight > 0) { // We'll distribute the adjustment across the spanned // relative rows and adjust other relative row heights to // keep all relative row heights reconciled. final double unitAdjustment = adjustment / spannedRelativeWeight; for (int k = 0; k < rowSpan && i + k < rows.length; k++) { final double relativeWeight = relativeWeights[i + k]; if (relativeWeight > 0) { final double rowAdjustment = unitAdjustment * relativeWeight; rowHeights[i + k] += rowAdjustment; } } } else { // We'll distribute the adjustment evenly among the // intrinsic-height rows. for (int k = 0; k < rowSpan && i + k < rows.length; k++) { if (intrinsicHeightRows[i + k]) { final double rowAdjustment = adjustment / spannedIntrinsicHeightCellCount; rowHeights[i + k] += rowAdjustment; } } } } } } } } } // Finally, we adjust the heights of the relative rows upwards where // necessary to reconcile their heights relative to one another while // ensuring that they still get at least their intrinsic height. if (totalRelativeWeight > 0) { // Calculate total relative height after the required upward adjustments double totalRelativeHeight = 0; for (int i = 0; i < rows.length; i++) { final double relativeWeight = relativeWeights[i]; if (relativeWeight > 0) { final double rowHeight = rowHeights[i]; final double weightPercentage = relativeWeight / totalRelativeWeight; totalRelativeHeight = math.max( totalRelativeHeight, rowHeight / weightPercentage, ); } } // Perform the upward adjustments using the total relative height for (int i = 0; i < rows.length; i++) { final double relativeWeight = relativeWeights[i]; if (relativeWeight > 0) { final double weightPercentage = relativeWeight / totalRelativeWeight; rowHeights[i] = weightPercentage * totalRelativeHeight; } } } return rowHeights; } List<double> _computeActualRowHeights( LinearConstraints heightConstraints, List<double> columnWidths, ) { final double totalRelativeWeight = rows .map<TablePaneRowHeight>((RenderTableRow row) => row.height) .whereType<RelativeTablePaneRowHeight>() .map<double>( (RelativeTablePaneRowHeight heightSpec) => heightSpec.height, ) .fold<double>(0, _sum); final double totalWidth = _computeWidth(columnWidths); final List<double> rowHeights = _computeIntrinsicRowHeights( totalWidth, _computeIntrinsicChildHeight, ); double totalHeight = _computeHeight(rowHeights); void growRelativeRowsToMeetMinimumTotalHeight(double minimumHeight) { final double remainingHeight = minimumHeight - totalHeight; assert(remainingHeight >= 0); for (int i = 0; i < rows.length; i++) { final TablePaneRowHeight rowHeightSpec = rows[i].height; if (rowHeightSpec.isRelative) { final double relativeWeight = rowHeightSpec.height; final double weightPercentage = relativeWeight / totalRelativeWeight; assert(weightPercentage > 0 && weightPercentage <= 1); final double addHeight = remainingHeight * weightPercentage; rowHeights[i] += addHeight; totalHeight += addHeight; } } } if (heightConstraints.isSatisfiedBy(totalHeight)) { if (verticalRelativeSize == MainAxisSize.max && heightConstraints.isBounded && totalRelativeWeight > 0) { // Grow the relative-height rows to fill the max height constraint. growRelativeRowsToMeetMinimumTotalHeight(heightConstraints.max); } } else if (heightConstraints < totalHeight) { if (totalRelativeWeight > 0) { // Shrink the relative-height rows to meet the max height constraints. final double overflowHeight = totalHeight - heightConstraints.max; assert(overflowHeight >= 0); bool? excessiveOverflow; for (int i = 0; i < rows.length; i++) { final TablePaneRowHeight rowHeightSpec = rows[i].height; if (rowHeightSpec.isRelative) { final double relativeWeight = rowHeightSpec.height; final double weightPercentage = relativeWeight / totalRelativeWeight; assert(weightPercentage > 0 && weightPercentage <= 1); double subtractHeight = overflowHeight * weightPercentage; final bool localOverflow = subtractHeight > rowHeights[i]; assert( excessiveOverflow == null || excessiveOverflow == localOverflow, ); excessiveOverflow = (excessiveOverflow ?? false) || localOverflow; if (excessiveOverflow) { subtractHeight = rowHeights[i]; } rowHeights[i] -= subtractHeight; totalHeight -= subtractHeight; } } assert(excessiveOverflow == (heightConstraints < totalHeight)); if (excessiveOverflow!) { // TODO: handle overflow } } else { // TODO: handle overflow } } else if (heightConstraints > totalHeight) { if (totalRelativeWeight > 0) { // Grow the relative-height rows to meet the min height constraints. growRelativeRowsToMeetMinimumTotalHeight(heightConstraints.min); } } assert(() { if (rowHeights.any((double value) => value.isNegative)) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('RenderTablePane computed a negative-height row.'), ErrorDescription('This indicates a bug in RenderTablePane.'), ErrorSpacer(), DiagnosticsProperty<List<double>>( 'The computed row heights were', rowHeights, ), ErrorSpacer(), DiagnosticsProperty<Object>( 'The RenderTablePane in question was created by', debugCreator, style: DiagnosticsTreeStyle.errorProperty, ), ]); } return true; }()); return rowHeights; } List<double> _computeIntrinsicColumnWidths( _IntrinsicComputer computeIntrinsicCellWidth, ) { final List<double> columnWidths = List<double>.filled(columns.length, 0); final List<double> relativeWeights = List<double>.filled(columns.length, 0); final List<bool> intrinsicWidthColumns = List<bool>.filled( columns.length, false, ); // First, we calculate the base widths of the columns, giving relative // columns their intrinsic width. Spanning cells will be ignored in this // pass. double totalRelativeWeight = 0; for (int i = 0; i < columns.length; i++) { final TablePaneColumnWidth columnWidthSpec = columns[i].width; final double columnWidth = columnWidthSpec.width; final bool isRelative = columnWidthSpec.isRelative; final bool isIntrinsic = intrinsicWidthColumns[i] = columnWidth < 0; if (isRelative) { relativeWeights[i] = columnWidth; totalRelativeWeight += columnWidth; } if (isIntrinsic || isRelative) { columnWidths[i] = _computeIntrinsicColumnWidth( i, computeIntrinsicCellWidth, ); } else { columnWidths[i] = columnWidth; } } // Next, we account for spanning cells, which have been ignored thus // far. If any spanned cell is intrinsic-width (including relative width // columns), then we ensure that the sum of the widths of the spanned // cells is enough to satisfy the intrinsic width of the spanning content for (int i = 0; i < rows.length; i++) { final RenderTableRow row = rows[i]; for (int j = 0, n = row.length; j < n && j < columns.length; j++) { final RenderBox child = row[j]; if (child is! RenderEmptyTableCell) { final TableCellParentData childParentData = child.parentData as TableCellParentData; final int columnSpan = childParentData.columnSpan; if (columnSpan > 1) { // We might need to adjust column widths to accommodate this // spanning cell. First, we find out if any of the spanned cells // are intrinsic width or relative width and how much space we've // allocated thus far for those cells. int spannedIntrinsicWidthCellCount = 0; double spannedRelativeWeight = 0; double spannedWidth = 0; for (int k = 0; k < columnSpan && j + k < columns.length; k++) { spannedRelativeWeight += relativeWeights[j + k]; spannedWidth += columnWidths[j + k]; if (intrinsicWidthColumns[j + k]) { spannedIntrinsicWidthCellCount++; } } if (spannedRelativeWeight > 0 || spannedIntrinsicWidthCellCount > 0) { bool isRelativeOrIntrinsic(TablePaneRowHeight spec) { return spec.isRelative || spec.height.isNegative; } final TablePaneRowHeight heightSpec = row.height; double heightConstraint; if (isRelativeOrIntrinsic(heightSpec)) { heightConstraint = double.infinity; } else { final int rowSpan = childParentData.rowSpan; final Iterable<TablePaneRowHeight> spannedRowHeights = rows .map<TablePaneRowHeight>((RenderTableRow row) => row.height) .skip(i) .take(rowSpan); if (spannedRowHeights.any(isRelativeOrIntrinsic)) { heightConstraint = double.infinity; } else { heightConstraint = spannedRowHeights .map<double>((TablePaneRowHeight spec) => spec.height) .fold<double>(0, _sum); heightConstraint += math.max(spannedRowHeights.length - 1, 0) * verticalSpacing; } } final double childIntrinsicWidth = computeIntrinsicCellWidth( child, heightConstraint, ); if (childIntrinsicWidth > spannedWidth) { // The child's intrinsic width is larger than the width we've // allocated thus far, so an adjustment is necessary. final double adjustment = childIntrinsicWidth - spannedWidth; if (spannedRelativeWeight > 0) { // We'll distribute the adjustment across the spanned // relative columns and adjust other relative column widths // to keep all relative column widths reconciled. final double unitAdjustment = adjustment / spannedRelativeWeight; for ( int k = 0; k < columnSpan && j + k < columns.length; k++ ) { final double relativeWeight = relativeWeights[j + k]; if (relativeWeight > 0) { final double columnAdjustment = unitAdjustment * relativeWeight; columnWidths[j + k] += columnAdjustment; } } } else { // We'll distribute the adjustment evenly among the // intrinsic-width columns. for ( int k = 0; k < columnSpan && j + k < columns.length; k++ ) { if (intrinsicWidthColumns[j + k]) { final double columnAdjustment = adjustment / spannedIntrinsicWidthCellCount; columnWidths[j + k] += columnAdjustment; } } } } } } } } } // Finally, we adjust the widths of the relative columns upwards where // necessary to reconcile their widths relative to one another while // ensuring that they still get at least their intrinsic width if (totalRelativeWeight > 0) { // Calculate total relative width after the required upward adjustments double totalRelativeWidth = 0; for (int i = 0; i < columns.length; i++) { final double relativeWeight = relativeWeights[i]; if (relativeWeight > 0) { final double columnWidth = columnWidths[i]; final double weightPercentage = relativeWeight / totalRelativeWeight; totalRelativeWidth = math.max( totalRelativeWidth, columnWidth / weightPercentage, ); } } // Perform the upward adjustments using the total relative width for (int i = 0; i < columns.length; i++) { final double relativeWeight = relativeWeights[i]; if (relativeWeight > 0) { final double weightPercentage = relativeWeight / totalRelativeWeight; columnWidths[i] = weightPercentage * totalRelativeWidth; } } } return columnWidths; } List<double> _computeActualColumnWidths(LinearConstraints widthConstraints) { final double totalRelativeWeight = columns .map<TablePaneColumnWidth>((TablePaneColumn column) => column.width) .whereType<RelativeTablePaneColumnWidth>() .map<double>( (RelativeTablePaneColumnWidth widthSpec) => widthSpec.width, ) .fold<double>(0, _sum); final List<double> columnWidths = _computeIntrinsicColumnWidths( _computeIntrinsicChildWidth, ); double totalWidth = _computeWidth(columnWidths); void growRelativeColumnsToMeetMinimumTotalWidth(double minimumWidth) { final double remainingWidth = minimumWidth - totalWidth; assert(remainingWidth >= 0); for (int j = 0; j < columns.length; j++) { final TablePaneColumnWidth columnWidthSpec = columns[j].width; if (columnWidthSpec.isRelative) { final double relativeWeight = columnWidthSpec.width; final double weightPercentage = relativeWeight / totalRelativeWeight; assert(weightPercentage > 0 && weightPercentage <= 1); final double addWidth = remainingWidth * weightPercentage; columnWidths[j] += addWidth; totalWidth += addWidth; } } } if (widthConstraints.isSatisfiedBy(totalWidth)) { if (horizontalRelativeSize == MainAxisSize.max && widthConstraints.isBounded && totalRelativeWeight > 0) { // Grow the relative-width columns to fill the max width constraint. growRelativeColumnsToMeetMinimumTotalWidth(widthConstraints.max); } } else if (widthConstraints < totalWidth) { if (totalRelativeWeight > 0) { // Shrink the relative-width columns to meet the max width constraints. final double overflowWidth = totalWidth - widthConstraints.max; assert(overflowWidth >= 0); bool? excessiveOverflow; for (int j = 0; j < columns.length; j++) { final TablePaneColumnWidth columnWidthSpec = columns[j].width; if (columnWidthSpec.isRelative) { final double relativeWeight = columnWidthSpec.width; final double weightPercentage = relativeWeight / totalRelativeWeight; assert(weightPercentage > 0 && weightPercentage <= 1); double subtractWidth = overflowWidth * weightPercentage; final bool localOverflow = subtractWidth > columnWidths[j]; assert( excessiveOverflow == null || excessiveOverflow == localOverflow, ); excessiveOverflow = (excessiveOverflow ?? false) || localOverflow; if (excessiveOverflow) { subtractWidth = columnWidths[j]; } columnWidths[j] -= subtractWidth; totalWidth -= subtractWidth; } } assert(excessiveOverflow == (widthConstraints < totalWidth)); if (excessiveOverflow!) { // TODO: handle overflow } } else { // TODO: handle overflow } } else if (widthConstraints > totalWidth) { if (totalRelativeWeight > 0) { // Grow the relative-width columns to meet the min width constraints. growRelativeColumnsToMeetMinimumTotalWidth(widthConstraints.min); } } assert(() { if (columnWidths.any((double value) => value.isNegative)) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('RenderTablePane computed a negative-width column.'), ErrorDescription('This indicates a bug in RenderTablePane.'), ErrorSpacer(), DiagnosticsProperty<List<double>>( 'The computed column widths were', columnWidths, ), ErrorSpacer(), DiagnosticsProperty<Object>( 'The RenderTablePane in question was created by', debugCreator, style: DiagnosticsTreeStyle.errorProperty, ), ]); } return true; }()); return columnWidths; } double _computeHeight(List<double> rowHeights) { return rowHeights.fold<double>(0, _sum) + math.max(rows.length - 1, 0) * verticalSpacing; } double _computeIntrinsicHeight( double width, _IntrinsicComputer computeIntrinsicCellHeight, ) { return _computeHeight( _computeIntrinsicRowHeights(width, computeIntrinsicCellHeight), ); } double _computeIntrinsicChildHeight(RenderBox child, double width) { switch (verticalIntrinsicSize) { case MainAxisSize.min: return child.getMinIntrinsicHeight(width); case MainAxisSize.max: return child.getMaxIntrinsicHeight(width); } } double _computeMinIntrinsicChildHeight(RenderBox child, double width) { return child.getMinIntrinsicHeight(width); } double _computeMaxIntrinsicChildHeight(RenderBox child, double width) { return child.getMaxIntrinsicHeight(width); } double _computeWidth(List<double> columnWidths) { return columnWidths.fold<double>(0, _sum) + math.max(columns.length - 1, 0) * horizontalSpacing; } double _computeIntrinsicWidth( double height, _IntrinsicComputer computeIntrinsicCellWidth, ) { return _computeWidth( _computeIntrinsicColumnWidths(computeIntrinsicCellWidth), ); } double _computeIntrinsicChildWidth(RenderBox child, double height) { switch (horizontalIntrinsicSize) { case MainAxisSize.min: return child.getMinIntrinsicWidth(height); case MainAxisSize.max: return child.getMaxIntrinsicWidth(height); } } double _computeMinIntrinsicChildWidth(RenderBox child, double height) { return child.getMinIntrinsicWidth(height); } double _computeMaxIntrinsicChildWidth(RenderBox child, double height) { return child.getMaxIntrinsicWidth(height); } @protected List<RenderTableRow> get rows => children.cast<RenderTableRow>(); @override void setupParentData(RenderBox child) { if (child.parentData is! TableRowParentData) { child.parentData = TableRowParentData(); } } @override void attach(PipelineOwner owner) { super.attach(owner); if (metricsController != null) { metricsController!._attach(this); } } @override void detach() { super.detach(); if (metricsController != null) { metricsController!._detach(); } } @override @protected void markNeedsChildren() { super.markNeedsChildren(); markNeedsMetrics(); } @override @protected double computeMinIntrinsicHeight(double width) { return _computeIntrinsicHeight(width, _computeMinIntrinsicChildHeight); } @override @protected double computeMaxIntrinsicHeight(double width) { return _computeIntrinsicHeight(width, _computeMaxIntrinsicChildHeight); } @override @protected double computeMinIntrinsicWidth(double height) { return _computeIntrinsicWidth(height, _computeMinIntrinsicChildWidth); } @override @protected double computeMaxIntrinsicWidth(double height) { return _computeIntrinsicWidth(height, _computeMaxIntrinsicChildWidth); } @override @protected double? computeDistanceToActualBaseline(TextBaseline baseline) { return defaultComputeDistanceToFirstActualBaseline(baseline); } @override @protected bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } bool _needsMetrics = true; _TablePaneMetrics? _metrics; @protected @visibleForTesting _TablePaneMetrics get metrics => _metrics!; @protected void markNeedsMetrics() { _needsMetrics = true; markNeedsLayout(); } @protected void calculateMetricsIfNecessary() { assert(debugDoingThisLayout); if (_needsMetrics || metrics.constraints != constraints) { _metrics = _TablePaneMetrics(this); _needsMetrics = false; if (metricsController != null) { metricsController!._notify(); } } } @override void performLayout() { calculateMetricsIfNecessary(); size = constraints.constrainDimensions( _computeWidth(metrics.columnWidths), _computeHeight(metrics.rowHeights), ); assert(() { if (rows.isNotEmpty) { final int cellsPerRow = rows.first.children.length; if (rows.any( (RenderTableRow row) => row.children.length != cellsPerRow, )) { final Iterable<int> rowLengths = rows.map<int>((RenderTableRow row) { return row.length; }); throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('RenderTablePane contains irregular row lengths.'), ErrorDescription( 'Every TableRow in a TablePane must have the same number of ' 'children, so that every table cell is filled. Otherwise, the table will ' 'contain holes.', ), ErrorDescription( 'The counts of cells per row in this TablePane were: $rowLengths', ), ErrorSpacer(), DiagnosticsProperty<Object>( 'The RenderTablePane in question was created by', debugCreator, style: DiagnosticsTreeStyle.errorProperty, ), ]); } if (cellsPerRow != columns.length) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('RenderTablePane cells do not match columns.'), ErrorDescription( 'The number of children inside every TableRow must match the ' 'number of columns specified for the TablePane.', ), ErrorSpacer(), IntProperty( 'The number of cells in each row was', cellsPerRow, style: DiagnosticsTreeStyle.errorProperty, ), IntProperty( 'The number of columns was', columns.length, style: DiagnosticsTreeStyle.errorProperty, ), ErrorSpacer(), DiagnosticsProperty<Object>( 'The RenderTablePane in question was created by', debugCreator, style: DiagnosticsTreeStyle.errorProperty, ), ]); } } return true; }()); double childY = 0; for (int i = 0; i < rows.length; i++) { final RenderTableRow row = rows[i]; final List<BoxConstraints> cellConstraints = <BoxConstraints>[]; final List<Offset> cellPositions = <Offset>[]; double childX = 0; double expandedRowWidth = 0; double expandedRowHeight = 0; for (int j = 0; j < row.length && j < columns.length; j++) { final RenderBox child = row[j]; if (child is RenderEmptyTableCell) { cellConstraints.add(BoxConstraints.tight(Size.zero)); cellPositions.add(Offset(childX, 0)); } else { final TableCellParentData childParentData = child.parentData as TableCellParentData; final int columnSpan = math.min( childParentData.columnSpan, columns.length - j, ); double childWidth = metrics.columnWidths .skip(j) .take(columnSpan) .fold<double>(0, _sum); childWidth += (columnSpan - 1) * horizontalSpacing; final int rowSpan = math.min( childParentData.rowSpan, rows.length - i, ); double childHeight = metrics.rowHeights .skip(i) .take(rowSpan) .fold<double>(0, _sum); childHeight += (rowSpan - 1) * verticalSpacing; // Set the child's size childWidth = math.max(childWidth, 0); childHeight = math.max(childHeight, 0); cellConstraints.add( BoxConstraints.tightFor(width: childWidth, height: childHeight), ); cellPositions.add(Offset(childX, 0)); expandedRowWidth = math.max(expandedRowWidth, childX + childWidth); expandedRowHeight = math.max(expandedRowHeight, childHeight); } childX += (metrics.columnWidths[j] + horizontalSpacing); } row.layout( TableRowConstraints.tightFor( width: expandedRowWidth, height: expandedRowHeight, cellConstraints: cellConstraints, cellPositions: cellPositions, ), ); final TableRowParentData rowParentData = row.parentData as TableRowParentData; rowParentData.offset = Offset(0, childY); childY += (metrics.rowHeights[i] + verticalSpacing); } } @override void paint(PaintingContext context, Offset offset) { defaultPaint(context, offset); } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('horizontalSpacing', horizontalSpacing)); properties.add(DoubleProperty('verticalSpacing', verticalSpacing)); properties.add( EnumProperty<MainAxisSize>( 'horizontalIntrinsicSize', horizontalIntrinsicSize, ), ); properties.add( EnumProperty<MainAxisSize>( 'horizontalRelativeSize', horizontalRelativeSize, ), ); properties.add( EnumProperty<MainAxisSize>( 'verticalIntrinsicSize', verticalIntrinsicSize, ), ); properties.add( EnumProperty<MainAxisSize>('verticalRelativeSize', verticalRelativeSize), ); properties.add( DiagnosticsProperty<_TablePaneMetrics?>('metrics', _metrics), ); } } class TablePaneMetricsController extends ChangeNotifier { RenderTablePane? _renderObject; void _attach(RenderTablePane renderObject) { assert(_renderObject == null); assert(renderObject.attached); _renderObject = renderObject; notifyListeners(); } void _detach() { assert(_renderObject != null); _renderObject = null; notifyListeners(); } void _notify() { assert(hasMetrics); notifyListeners(); } bool get hasMetrics => _renderObject != null && _renderObject!._metrics != null; int? getRowAt(double y) { assert(hasMetrics); final double verticalSpacing = _renderObject!.verticalSpacing; final List<double> rowHeights = _renderObject!._metrics!.rowHeights; double top = 0; for (int i = 0; i < rowHeights.length; i++) { final double bottom = top + rowHeights[i]; if (y >= top && y <= bottom) { return i; } top = bottom + verticalSpacing; } return null; } Rect? getRowBounds(int row) { assert(hasMetrics); final double verticalSpacing = _renderObject!.verticalSpacing; final List<double> rowHeights = _renderObject!._metrics!.rowHeights; if (row < 0 || row >= rowHeights.length) { return null; } final double top = rowHeights.take(row).fold<double>(0, _sum) + row * verticalSpacing; return Rect.fromLTWH(0, top, _renderObject!.size.width, rowHeights[row]); } int? getColumnAt(double x) { assert(hasMetrics); final double horizontalSpacing = _renderObject!.horizontalSpacing; final List<double> columnWidths = _renderObject!._metrics!.columnWidths; double left = 0; for (int j = 0; j < columnWidths.length; j++) { final double right = left + columnWidths[j]; if (x >= left && x <= right) { return j; } left = right + horizontalSpacing; } return null; } Rect? getColumnBounds(int column) { assert(hasMetrics); final double horizontalSpacing = _renderObject!.horizontalSpacing; final List<double> columnWidths = _renderObject!._metrics!.columnWidths; if (column < 0 || column >= columnWidths.length) { return null; } final double left = columnWidths.take(column).fold<double>(0, _sum) + column * horizontalSpacing; return Rect.fromLTWH( left, 0, columnWidths[column], _renderObject!.size.height, ); } } class _TablePaneMetrics with Diagnosticable { const _TablePaneMetrics._( this.constraints, this.columnWidths, this.rowHeights, ); factory _TablePaneMetrics(RenderTablePane tablePane) { final BoxConstraints constraints = tablePane.constraints; final LinearConstraints widthConstraints = LinearConstraints.width( constraints, ); final LinearConstraints heightConstraints = LinearConstraints.height( constraints, ); List<double> columnWidths = tablePane._computeActualColumnWidths( widthConstraints, ); List<double> rowHeights = tablePane._computeActualRowHeights( heightConstraints, columnWidths, ); return _TablePaneMetrics._(constraints, columnWidths, rowHeights); } final BoxConstraints constraints; final List<double> columnWidths; final List<double> rowHeights; @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add( DiagnosticsProperty<BoxConstraints>('constraints', constraints), ); properties.add( DiagnosticsProperty<List<double>>('columnWidths', columnWidths), ); properties.add(DiagnosticsProperty<List<double>>('rowHeights', rowHeights)); } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/table_view.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart' hide TableColumnWidth; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart' hide ScrollController, TableColumnWidth; import 'basic_table_view.dart'; import 'deferred_layout.dart'; import 'foundation.dart'; import 'listener_list.dart'; import 'navigator_listener.dart'; import 'scroll_pane.dart'; import 'segment.dart'; import 'sorting.dart'; import 'span.dart'; const double _kResizeHandleTargetPixels = 10; // logical /// Signature for a function that renders headers in a [ScrollableTableView]. /// /// Header builders are properties of the [TableColumn], so each /// column specifies the builder for that column's header. /// /// See also: /// * [TableCellBuilder], which renders table body cells. typedef TableHeaderBuilder = Widget Function(BuildContext context, int columnIndex); /// Signature for a function that renders cells in a [ScrollableTableView]. /// /// Cell builders are properties of the [TableColumn], so each /// column specifies the cell builder for cells in that column. /// /// The `rowSelected` argument specifies whether the row is currently selected, /// as indicated by the [TableViewSelectionController] that's associated with /// the table view. /// /// The `rowHighlighted` argument specifies whether the row is highlighted, /// typically because the table view allows selection of rows, and a mouse /// cursor is currently hovering over the row. /// /// The `isEditing` argument specifies whether row editing is currently active /// on the specified cell. /// /// See also: /// * [TableHeaderBuilder], which renders a column's header. /// * [TableViewSelectionController.selectMode], which dictates whether rows /// are eligible to become highlighted. /// * [BasicTableCellBuilder], the equivalent cell builder for a /// [BasicTableView]. typedef TableCellBuilder = Widget Function( BuildContext context, int rowIndex, int columnIndex, bool hasFocus, bool isRowSelected, bool isRowHighlighted, bool isEditing, bool isRowDisabled, ); typedef PreviewTableViewEditStartedHandler = Vote Function( TableViewEditorController controller, int rowIndex, int columnIndex, ); typedef TableViewEditStartedHandler = void Function(TableViewEditorController controller); typedef PreviewTableViewEditFinishedHandler = Vote Function(TableViewEditorController controller); typedef TableViewEditFinishedHandler = void Function( TableViewEditorController controller, TableViewEditOutcome outcome, ); typedef RowDoubleTapHandler = void Function(int row); @immutable class TableViewEditorListener { const TableViewEditorListener({ this.onPreviewEditStarted = _defaultOnPreviewEditStarted, this.onEditStarted = _defaultOnEditStarted, this.onPreviewEditFinished = _defaultOnPreviewEditFinished, this.onEditFinished = _defaultOnEditFinished, }); final PreviewTableViewEditStartedHandler onPreviewEditStarted; final TableViewEditStartedHandler onEditStarted; final PreviewTableViewEditFinishedHandler onPreviewEditFinished; final TableViewEditFinishedHandler onEditFinished; static Vote _defaultOnPreviewEditStarted( TableViewEditorController _, int __, int ___, ) { return Vote.approve; } static void _defaultOnEditStarted(TableViewEditorController _) { // No-op } static Vote _defaultOnPreviewEditFinished(TableViewEditorController _) { return Vote.approve; } static void _defaultOnEditFinished( TableViewEditorController _, TableViewEditOutcome __, ) { // No-op } } enum TableViewEditorBehavior { /// When initiating an edit of a table cell via /// [TableViewEditorController.beginEditing], re-render all cells in the row, /// and set the `isEditing` [TableCellBuilder] flag to true for all cells in /// the row. wholeRow, /// When initiating an edit of a table cell via /// [TableViewEditorController.beginEditing], re-render only the requested /// cell, and set the `isEditing` [TableCellBuilder] flag to true for only /// that cell and not any other cells in the row. singleCell, /// Disable table cell editing. /// /// This can also be accomplished by setting no [TableViewEditorController] /// on the [TableView]. none, } enum TableViewEditOutcome { saved, canceled } class TableViewEditorController with ListenerNotifier<TableViewEditorListener> { TableViewEditorController({this.behavior = TableViewEditorBehavior.wholeRow}); /// The editing behavior when an edit begins via [beginEditing]. final TableViewEditorBehavior behavior; /// True if this controller is associated with a table view. /// /// A controller may only be associated with one table view at a time. RenderTableView? _renderObject; bool get isAttached => _renderObject != null; @protected @mustCallSuper void attach(RenderTableView renderObject) { assert(!isAttached); _renderObject = renderObject; } @protected @mustCallSuper void detach() { assert(isAttached); _renderObject = null; } int? _rowIndex; int? _columnIndex; TableCellRange get cellsBeingEdited { assert(isAttached); if (!isEditing) { return const EmptyTableCellRange(); } switch (behavior) { case TableViewEditorBehavior.singleCell: return SingleCellRange(_rowIndex!, _columnIndex!); case TableViewEditorBehavior.wholeRow: return TableCellRect.fromLTRB( 0, _rowIndex!, _renderObject!.columns.length - 1, _rowIndex!, ); case TableViewEditorBehavior.none: assert(false); break; } throw StateError('Unreachable'); } /// True if an edit is currently in progress. /// /// If this is true, [editRowIndex] will be non-null. bool get isEditing { assert((_rowIndex == null) == (_columnIndex == null)); return _rowIndex != null; } bool isEditingCell(int rowIndex, int columnIndex) { if (behavior == TableViewEditorBehavior.none) { return false; } bool result = rowIndex == _rowIndex; if (result && behavior == TableViewEditorBehavior.singleCell) { result &= columnIndex == _columnIndex; } return result; } @mustCallSuper bool start(int rowIndex, int columnIndex) { assert(!isEditing); assert(isAttached); assert(rowIndex >= 0 && rowIndex < _renderObject!.length); assert(columnIndex >= 0 && columnIndex < _renderObject!.columns.length); assert(behavior != TableViewEditorBehavior.none); Vote vote = Vote.approve; notifyListeners((TableViewEditorListener listener) { vote = vote.tally( listener.onPreviewEditStarted(this, rowIndex, columnIndex), ); }); if (vote == Vote.approve) { _rowIndex = rowIndex; _columnIndex = columnIndex; notifyListeners((TableViewEditorListener listener) { listener.onEditStarted(this); }); return true; } else { return false; } } @mustCallSuper bool save() { assert(isEditing); assert(isAttached); Vote vote = Vote.approve; notifyListeners((TableViewEditorListener listener) { vote = vote.tally(listener.onPreviewEditFinished(this)); }); if (vote == Vote.approve) { notifyListeners((TableViewEditorListener listener) { listener.onEditFinished(this, TableViewEditOutcome.saved); }); _rowIndex = null; _columnIndex = null; return true; } else { return false; } } @mustCallSuper void cancel() { assert(isEditing); assert(isAttached); notifyListeners((TableViewEditorListener listener) { listener.onEditFinished(this, TableViewEditOutcome.canceled); }); _rowIndex = null; _columnIndex = null; } } /// Holds the properties of a column in a [ScrollableTableView]. /// /// Mutable properties such as [width] and [sortDirection] will notify /// listeners when changed. class TableColumn extends AbstractTableColumn with ChangeNotifier { TableColumn({ required this.key, required this.cellBuilder, this.prototypeCellBuilder, this.headerBuilder, TableColumnWidth width = const FlexTableColumnWidth(), }) : _width = width; /// A unique identifier for this column. /// /// This is the key by which we sort columns in [TableViewSortController]. final String key; /// The builder responsible for the look & feel of cells in this column. final TableCellBuilder cellBuilder; /// The builder responsible for building the "prototype cell" for this /// column. /// /// The prototype cell is a cell with sample data that is appropriate for the /// column. The prototype cells for every column join to form a "prototype /// row". The prototype row is used for things like calculating the fixed /// row height of a table view or for calculating a table view's baseline. /// /// Prototype cells are rendered in a standalone widget tree, so any widgets /// that require inherited data (such a [DefaultTextStyle] or /// [Directionality]) should be explicitly passed such information, or the /// builder should explicitly include such inherited widgets in the built /// hierarchy. /// /// If this is not specified, this column wll not contribute data towards the /// prototype row. If the prototype row contains no cells, then the table /// view will report no baseline. final WidgetBuilder? prototypeCellBuilder; /// The builder responsible for the look & feel of the header for this column. /// /// See also: /// /// * [ScrollableTableView.includeHeader], which if false will allow for /// this field to be null. final TableHeaderBuilder? headerBuilder; TableColumnWidth _width; /// The width specification for the column. /// /// Instances of [ConstrainedTableColumnWidth] will cause a column to become /// resizable. /// /// Changing this value will notify listeners. @override TableColumnWidth get width => _width; set width(TableColumnWidth value) { if (value == _width) return; _width = value; notifyListeners(); } @override int get hashCode => Object.hash(super.hashCode, cellBuilder, headerBuilder); @override bool operator ==(Object other) { if (identical(this, other)) return true; return super == other && other is TableColumn && cellBuilder == other.cellBuilder && headerBuilder == other.headerBuilder; } } class TableViewSelectionController with ChangeNotifier { TableViewSelectionController({this.selectMode = SelectMode.single}); /// TODO: document final SelectMode selectMode; ListSelection _selectedRanges = ListSelection(); RenderTableView? _renderObject; /// True if this controller is associated with a table view. /// /// A selection controller may only be associated with one table view at a /// time. bool get isAttached => _renderObject != null; @protected @mustCallSuper void attach(RenderTableView renderObject) { assert(!isAttached); _renderObject = renderObject; } @protected @mustCallSuper void detach() { assert(isAttached); _renderObject = null; } /// TODO: document int get selectedIndex { assert(selectMode == SelectMode.single); return _selectedRanges.isEmpty ? -1 : _selectedRanges[0].start; } set selectedIndex(int index) { if (index == -1) { clearSelection(); } else { selectedRange = Span.single(index); } } /// TODO: document Span? get selectedRange { assert(_selectedRanges.length <= 1); return _selectedRanges.isEmpty ? null : _selectedRanges[0]; } set selectedRange(Span? range) { if (range == null) { clearSelection(); } else { selectedRanges = <Span>[range]; } } /// TODO: document Iterable<Span> get selectedRanges { return _selectedRanges.data; } set selectedRanges(Iterable<Span> ranges) { assert(selectMode != SelectMode.none, 'Selection is not enabled'); assert(() { if (selectMode == SelectMode.single) { if (ranges.length > 1) { return false; } if (ranges.isNotEmpty) { final Span range = ranges.single; if (range.length > 1) { return false; } } } return true; }()); final ListSelection selectedRanges = ListSelection(); for (Span range in ranges) { assert( range.start >= 0 && (!isAttached || range.end < _renderObject!.length), ); selectedRanges.addRange(range.start, range.end); } _selectedRanges = selectedRanges; notifyListeners(); } int get firstSelectedIndex => _selectedRanges.isNotEmpty ? _selectedRanges.first.start : -1; int get lastSelectedIndex => _selectedRanges.isNotEmpty ? _selectedRanges.last.end : -1; bool addSelectedIndex(int index) { final List<Span> addedRanges = addSelectedRange(index, index); return addedRanges.isNotEmpty; } List<Span> addSelectedRange(int start, int end) { assert(selectMode == SelectMode.multi); assert(start >= 0 && (!isAttached || end < _renderObject!.length)); final List<Span> addedRanges = _selectedRanges.addRange(start, end); notifyListeners(); return addedRanges; } bool removeSelectedIndex(int index) { List<Span> removedRanges = removeSelectedRange(index, index); return removedRanges.isNotEmpty; } List<Span> removeSelectedRange(int start, int end) { assert(selectMode == SelectMode.multi); assert(start >= 0 && (!isAttached || end < _renderObject!.length)); final List<Span> removedRanges = _selectedRanges.removeRange(start, end); notifyListeners(); return removedRanges; } void selectAll() { assert(isAttached); selectedRange = Span(0, _renderObject!.length - 1); } void clearSelection() { if (_selectedRanges.isNotEmpty) { _selectedRanges = ListSelection(); notifyListeners(); } } bool isRowSelected(int rowIndex) { assert(rowIndex >= 0 && isAttached && rowIndex < _renderObject!.length); return _selectedRanges.containsIndex(rowIndex); } } enum TableViewSortMode { none, singleColumn, multiColumn } typedef TableViewSortAddedHandler = void Function(TableViewSortController controller, String key); typedef TableViewSortUpdatedHandler = void Function( TableViewSortController controller, String key, SortDirection? previousSortDirection, ); typedef TableViewSortChangedHandler = void Function(TableViewSortController controller); class TableViewSortListener { const TableViewSortListener({ this.onAdded = _defaultOnAdded, this.onUpdated = _defaultOnUpdated, this.onChanged = _defaultOnChanged, }); final TableViewSortAddedHandler onAdded; final TableViewSortUpdatedHandler onUpdated; final TableViewSortChangedHandler onChanged; static void _defaultOnAdded(TableViewSortController _, String __) {} static void _defaultOnUpdated( TableViewSortController _, String __, SortDirection? ___, ) {} static void _defaultOnChanged(TableViewSortController _) {} } class TableViewSortController with ListenerNotifier<TableViewSortListener> { TableViewSortController({this.sortMode = TableViewSortMode.singleColumn}); final TableViewSortMode sortMode; final LinkedHashMap<String, SortDirection> _sortMap = LinkedHashMap<String, SortDirection>(); SortDirection? operator [](String columnKey) => _sortMap[columnKey]; operator []=(String columnKey, SortDirection? direction) { assert(sortMode != TableViewSortMode.none); final SortDirection? previousDirection = _sortMap[columnKey]; if (previousDirection == direction) { return; } else if (sortMode == TableViewSortMode.singleColumn) { final Map<String, SortDirection> newMap = <String, SortDirection>{}; if (direction != null) { newMap[columnKey] = direction; } replaceAll(newMap); } else { if (direction == null) { remove(columnKey); } else { _sortMap[columnKey] = direction; if (previousDirection == null) { notifyListeners( (TableViewSortListener listener) => listener.onAdded(this, columnKey), ); } else { notifyListeners((TableViewSortListener listener) { listener.onUpdated(this, columnKey, previousDirection); }); } } } } SortDirection? remove(String columnKey) { final SortDirection? previousDirection = _sortMap.remove(columnKey); if (previousDirection != null) { notifyListeners((TableViewSortListener listener) { listener.onUpdated(this, columnKey, null); }); } return previousDirection; } bool containsKey(String columnKey) => _sortMap.containsKey(columnKey); bool get isEmpty => _sortMap.isEmpty; bool get isNotEmpty => _sortMap.isNotEmpty; int get length => _sortMap.length; Iterable<String> get keys => _sortMap.keys; void replaceAll(Map<String, SortDirection> map) { _sortMap.clear(); for (MapEntry<String, SortDirection> entry in map.entries) { _sortMap[entry.key] = entry.value; } notifyListeners( (TableViewSortListener listener) => listener.onChanged(this), ); } } typedef TableViewRowDisabledFilterChangedHandler = void Function(Predicate<int>? previousFilter); class TableViewRowDisablerListener { const TableViewRowDisablerListener({ required this.onTableViewRowDisabledFilterChanged, }); final TableViewRowDisabledFilterChangedHandler? onTableViewRowDisabledFilterChanged; } class TableViewRowDisablerController with ListenerNotifier<TableViewRowDisablerListener> { TableViewRowDisablerController({Predicate<int>? filter}) : _filter = filter; Predicate<int>? _filter; Predicate<int>? get filter => _filter; set filter(Predicate<int>? value) { Predicate<int>? previousValue = _filter; if (value != previousValue) { _filter = value; notifyListeners((TableViewRowDisablerListener listener) { if (listener.onTableViewRowDisabledFilterChanged != null) { listener.onTableViewRowDisabledFilterChanged!(previousValue); } }); } } bool isRowDisabled(int rowIndex) => filter != null && filter!(rowIndex); } class ConstrainedTableColumnWidth extends TableColumnWidth { const ConstrainedTableColumnWidth({ required double width, this.minWidth = 0.0, this.maxWidth = double.infinity, }) : assert(width >= 0), assert(width < double.infinity), assert(minWidth >= 0), assert(maxWidth >= minWidth), super(width); final double minWidth; final double maxWidth; ConstrainedTableColumnWidth copyWith({ double? width, double? minWidth, double? maxWidth, }) { minWidth ??= this.minWidth; maxWidth ??= this.maxWidth; width ??= this.width; width = width.clamp(minWidth, maxWidth); return ConstrainedTableColumnWidth( width: width, minWidth: minWidth, maxWidth: maxWidth, ); } @override @protected void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('minWidth', minWidth)); properties.add(DoubleProperty('maxWidth', maxWidth)); } @override int get hashCode => Object.hash(super.hashCode, minWidth, maxWidth); @override bool operator ==(Object other) { if (identical(this, other)) return true; return super == other && other is ConstrainedTableColumnWidth && minWidth == other.minWidth && maxWidth == other.maxWidth; } } class ScrollableTableView extends StatelessWidget { const ScrollableTableView({ Key? key, required this.rowHeight, required this.length, required this.columns, this.metricsController, this.selectionController, this.sortController, this.editorController, this.rowDisabledController, this.platform, this.scrollController, this.roundColumnWidthsToWholePixel = false, this.includeHeader = true, this.onDoubleTapRow, this.focusNode, }) : super(key: key); final double rowHeight; final int length; final List<TableColumn> columns; final TableViewMetricsController? metricsController; final TableViewSelectionController? selectionController; final TableViewSortController? sortController; final TableViewEditorController? editorController; final TableViewRowDisablerController? rowDisabledController; final TargetPlatform? platform; final ScrollPaneController? scrollController; final bool roundColumnWidthsToWholePixel; final bool includeHeader; final RowDoubleTapHandler? onDoubleTapRow; final FocusNode? focusNode; @override Widget build(BuildContext context) { Widget? columnHeader; if (includeHeader) { columnHeader = TableViewHeader( rowHeight: rowHeight, columns: columns, sortController: sortController, roundColumnWidthsToWholePixel: roundColumnWidthsToWholePixel, ); } Widget table = TableView( length: length, rowHeight: rowHeight, columns: columns, roundColumnWidthsToWholePixel: roundColumnWidthsToWholePixel, metricsController: metricsController, selectionController: selectionController, sortController: sortController, editorController: editorController, rowDisabledController: rowDisabledController, platform: platform, onDoubleTapRow: onDoubleTapRow, focusNode: focusNode, ); return ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.expand, verticalScrollBarPolicy: ScrollBarPolicy.auto, controller: scrollController, columnHeader: columnHeader, view: table, ); } } typedef ObserveNavigator = NavigatorListenerRegistration Function({ NavigatorObserverCallback? onPushed, NavigatorObserverCallback? onPopped, NavigatorObserverCallback? onRemoved, NavigatorObserverOnReplacedCallback? onReplaced, NavigatorObserverCallback? onStartUserGesture, VoidCallback? onStopUserGesture, }); class TableView extends StatefulWidget { const TableView({ Key? key, required this.rowHeight, required this.length, required this.columns, this.metricsController, this.selectionController, this.editorController, this.sortController, this.rowDisabledController, this.roundColumnWidthsToWholePixel = false, this.platform, this.onDoubleTapRow, this.focusNode, }) : super(key: key); final double rowHeight; final int length; final List<TableColumn> columns; final TableViewMetricsController? metricsController; final TableViewSelectionController? selectionController; final TableViewEditorController? editorController; final TableViewSortController? sortController; final TableViewRowDisablerController? rowDisabledController; final bool roundColumnWidthsToWholePixel; final TargetPlatform? platform; final RowDoubleTapHandler? onDoubleTapRow; final FocusNode? focusNode; @override State<TableView> createState() => _TableViewState(); } class _TableViewState extends State<TableView> { FocusNode? _focusNode; FocusNode get focusNode => widget.focusNode ?? _focusNode!; @override void initState() { super.initState(); if (widget.focusNode == null) { _focusNode = FocusNode(); } } @override void didUpdateWidget(covariant TableView oldWidget) { super.didUpdateWidget(oldWidget); if (widget.focusNode != oldWidget.focusNode) { if (oldWidget.focusNode == null) { assert(_focusNode != null); _focusNode!.dispose(); _focusNode = null; } else if (widget.focusNode == null) { assert(_focusNode == null); _focusNode = FocusNode(); } } } @override void dispose() { _focusNode?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Focus( debugLabel: 'chicago.TableView', focusNode: focusNode, child: RawTableView( length: widget.length, rowHeight: widget.rowHeight, columns: widget.columns, roundColumnWidthsToWholePixel: widget.roundColumnWidthsToWholePixel, metricsController: widget.metricsController, selectionController: widget.selectionController, sortController: widget.sortController, editorController: widget.editorController, rowDisabledController: widget.rowDisabledController, platform: widget.platform, onDoubleTapRow: widget.onDoubleTapRow, focusNode: focusNode, ), ); } } class RawTableView extends RenderObjectWidget { const RawTableView({ Key? key, required this.rowHeight, required this.length, required this.columns, required this.focusNode, this.metricsController, this.selectionController, this.editorController, this.sortController, this.rowDisabledController, this.roundColumnWidthsToWholePixel = false, this.platform, this.onDoubleTapRow, }) : super(key: key); final double rowHeight; final int length; final List<TableColumn> columns; final FocusNode focusNode; final TableViewMetricsController? metricsController; final TableViewSelectionController? selectionController; final TableViewEditorController? editorController; final TableViewSortController? sortController; final TableViewRowDisablerController? rowDisabledController; final bool roundColumnWidthsToWholePixel; final TargetPlatform? platform; final RowDoubleTapHandler? onDoubleTapRow; @override TableViewElement createElement() => TableViewElement(this); @override @protected RenderTableView createRenderObject(BuildContext context) { return RenderTableView( rowHeight: rowHeight, length: length, columns: columns, focusNode: focusNode, roundColumnWidthsToWholePixel: roundColumnWidthsToWholePixel, metricsController: metricsController, selectionController: selectionController, sortController: sortController, editorController: editorController, rowDisabledController: rowDisabledController, platform: platform ?? defaultTargetPlatform, onDoubleTapRow: onDoubleTapRow, ); } @override @protected void updateRenderObject(BuildContext context, RenderTableView renderObject) { renderObject ..rowHeight = rowHeight ..length = length ..columns = columns ..focusNode = focusNode ..roundColumnWidthsToWholePixel = roundColumnWidthsToWholePixel ..metricsController = metricsController ..selectionController = selectionController ..sortController = sortController ..editorController = editorController ..rowDisabledController = rowDisabledController ..platform = platform ?? defaultTargetPlatform ..onDoubleTapRow = onDoubleTapRow; } } @visibleForTesting class TableViewElement extends RenderObjectElement with TableViewElementMixin { TableViewElement(RawTableView tableView) : super(tableView); @override RawTableView get widget => super.widget as RawTableView; @override RenderTableView get renderObject => super.renderObject as RenderTableView; @override @protected Widget renderCell(int rowIndex, int columnIndex) { final TableColumn column = widget.columns[columnIndex]; return column.cellBuilder( this, rowIndex, columnIndex, widget.focusNode.hasFocus, widget.selectionController?.isRowSelected(rowIndex) ?? false, renderObject.highlightedRow == rowIndex, widget.editorController?.isEditingCell(rowIndex, columnIndex) ?? false, widget.rowDisabledController?.isRowDisabled(rowIndex) ?? false, ); } @override @protected Widget? buildPrototypeCell(int columnIndex) { final TableColumn column = widget.columns[columnIndex]; return column.prototypeCellBuilder != null ? column.prototypeCellBuilder!(this) : null; } @override void mount(Element? parent, dynamic newSlot) { super.mount(parent, newSlot); renderObject.updateObserveNavigatorCallback(_observeNavigator); } NavigatorListenerRegistration _observeNavigator({ NavigatorObserverCallback? onPushed, NavigatorObserverCallback? onPopped, NavigatorObserverCallback? onRemoved, NavigatorObserverOnReplacedCallback? onReplaced, NavigatorObserverCallback? onStartUserGesture, VoidCallback? onStopUserGesture, }) { return NavigatorListener.of(this).addObserver( onPushed: onPushed, onPopped: onPopped, onRemoved: onRemoved, onReplaced: onReplaced, onStartUserGesture: onStartUserGesture, onStopUserGesture: onStopUserGesture, ); } } @visibleForTesting class RenderTableView extends RenderSegment with RenderTableViewMixin, TableViewColumnListenerMixin, TableViewSortingMixin, DeferredLayoutMixin implements MouseTrackerAnnotation { RenderTableView({ required double rowHeight, required int length, required List<TableColumn> columns, required FocusNode focusNode, bool roundColumnWidthsToWholePixel = false, TableViewMetricsController? metricsController, TableViewSelectionController? selectionController, TableViewSortController? sortController, TableViewEditorController? editorController, TableViewRowDisablerController? rowDisabledController, TargetPlatform? platform, RowDoubleTapHandler? onDoubleTapRow, }) { initializeSortListener(); _editorListener = TableViewEditorListener( onEditStarted: _handleEditStarted, onEditFinished: _handleEditFinished, ); _rowDisablerListener = TableViewRowDisablerListener( onTableViewRowDisabledFilterChanged: _handleRowDisabledFilterChanged, ); this.rowHeight = rowHeight; this.length = length; this.columns = columns; this.focusNode = focusNode; this.roundColumnWidthsToWholePixel = roundColumnWidthsToWholePixel; this.metricsController = metricsController; this.selectionController = selectionController; this.sortController = sortController; this.editorController = editorController; this.rowDisabledController = rowDisabledController; this.platform = platform ?? defaultTargetPlatform; this.onDoubleTapRow = onDoubleTapRow; } late TableViewEditorListener _editorListener; late TableViewRowDisablerListener _rowDisablerListener; SerialTapGestureRecognizer? _serialTap; void _initSerialTap() { if (isSelectionEnabled || isEditingEnabled || onDoubleTapRow != null) { _serialTap = SerialTapGestureRecognizer()..onSerialTapUp = _handleSerialTapUp; } } void _disposeSerialTap() { _serialTap?.dispose(); _serialTap = null; } Set<int> _sortedColumns = <int>{}; void _resetSortedColumns() { _sortedColumns.clear(); if (sortController != null) { for (int i = 0; i < columns.length; i++) { if (sortController![columns[i].key] != null) { _sortedColumns.add(i); } } } } void _cancelEditIfNecessary() { if (_editorController != null && _editorController!.isEditing) { _editorController!.cancel(); } } @override set length(int value) { int? previousValue = rawLength; super.length = value; if (length != previousValue) { _cancelEditIfNecessary(); } } @override set columns(List<TableColumn> value) { List<TableColumn>? previousValue = rawColumns; super.columns = value; if (columns != previousValue) { _cancelEditIfNecessary(); } } @override set sortController(TableViewSortController? value) { TableViewSortController? previousValue = sortController; super.sortController = value; if (sortController != previousValue) { _resetSortedColumns(); _cancelEditIfNecessary(); } } FocusNode? _focusNode; FocusNode get focusNode => _focusNode!; set focusNode(FocusNode value) { if (_focusNode == value) return; if (_focusNode != null && attached) { _focusNode!.removeListener(_handleFocusChange); } _focusNode = value; if (attached) { value.addListener(_handleFocusChange); } markNeedsBuild(); } bool get isSelectionEnabled { return selectionController != null && selectionController!.selectMode != SelectMode.none; } TableViewSelectionController? _selectionController; TableViewSelectionController? get selectionController => _selectionController; set selectionController(TableViewSelectionController? value) { if (_selectionController == value) return; if (attached) { _disposeSerialTap(); } if (_selectionController != null) { if (attached) { _selectionController!.detach(); } _selectionController!.removeListener(_handleSelectionChanged); } _selectionController = value; if (_selectionController != null) { if (attached) { _selectionController!.attach(this); } _selectionController!.addListener(_handleSelectionChanged); } if (attached) { _initSerialTap(); } markNeedsBuild(); } bool get isEditingEnabled { return editorController != null && editorController!.behavior != TableViewEditorBehavior.none; } bool get isEditing => _editorController != null && _editorController!.isEditing; TableViewEditorController? _editorController; TableViewEditorController? get editorController => _editorController; set editorController(TableViewEditorController? value) { if (_editorController == value) return; if (attached) { _disposeSerialTap(); } if (_editorController != null) { _cancelEditIfNecessary(); if (attached) { _editorController!.detach(); } _editorController!.removeListener(_editorListener); } _editorController = value; if (_editorController != null) { if (attached) { _editorController!.attach(this); } _editorController!.addListener(_editorListener); } if (attached) { _initSerialTap(); } markNeedsBuild(); } TableViewRowDisablerController? _rowDisabledController; TableViewRowDisablerController? get rowDisabledController => _rowDisabledController; set rowDisabledController(TableViewRowDisablerController? value) { if (value != _rowDisabledController) { _cancelEditIfNecessary(); if (_rowDisabledController != null) { _rowDisabledController!.removeListener(_rowDisablerListener); } _rowDisabledController = value; if (_rowDisabledController != null) { _rowDisabledController!.addListener(_rowDisablerListener); } markNeedsBuild(); } } bool _isRowDisabled(int rowIndex) => _rowDisabledController?.isRowDisabled(rowIndex) ?? false; late ObserveNavigator _observeNavigator; @protected void updateObserveNavigatorCallback(ObserveNavigator callback) { _observeNavigator = callback; _cancelEditIfNecessary(); } TargetPlatform? _platform; TargetPlatform get platform => _platform!; set platform(TargetPlatform value) { if (value == _platform) return; _platform = value; } RowDoubleTapHandler? _onDoubleTapRow; RowDoubleTapHandler? get onDoubleTapRow => _onDoubleTapRow; set onDoubleTapRow(RowDoubleTapHandler? value) { if (value == _onDoubleTapRow) return; _onDoubleTapRow = value; if (attached) { _disposeSerialTap(); _initSerialTap(); } } bool get isHighlightEnabled => isSelectionEnabled; int? _highlightedRow; int? get highlightedRow => _highlightedRow; set highlightedRow(int? value) { if (_highlightedRow == value) return; final int? previousValue = _highlightedRow; _highlightedRow = value; final UnionTableCellRange dirtyCells = UnionTableCellRange(); if (previousValue != null) { dirtyCells.add( TableCellRect.fromLTRB( 0, previousValue, columns.length - 1, previousValue, ), ); } if (value != null) { dirtyCells.add( TableCellRect.fromLTRB(0, value, columns.length - 1, value), ); } markCellsDirty(dirtyCells); } /// Local cache of the cells being edited, so that we know which cells to /// mark dirty when the edit finishes. TableCellRange? _cellsBeingEdited; NavigatorListenerRegistration? _navigatorListenerRegistration; int _routesPushedDuringEdit = 0; void _handleFocusChange() { markNeedsBuild(); } void _handleEditStarted(TableViewEditorController controller) { assert(controller == _editorController); assert(_cellsBeingEdited == null); assert(_navigatorListenerRegistration == null); _disposeSerialTap(); _cellsBeingEdited = controller.cellsBeingEdited; markCellsDirty(_cellsBeingEdited!); GestureBinding.instance.pointerRouter.addGlobalRoute( _handleGlobalPointerEvent, ); _navigatorListenerRegistration = _observeNavigator( onPushed: _handleRoutePushedDuringEditing, onPopped: _handleRoutePoppedDuringEditing, ); } void _handleRoutePushedDuringEditing( Route<dynamic> route, Route<dynamic>? previousRoute, ) { assert(_routesPushedDuringEdit >= 0); if (_routesPushedDuringEdit++ == 0) { GestureBinding.instance.pointerRouter.removeGlobalRoute( _handleGlobalPointerEvent, ); } } void _handleRoutePoppedDuringEditing( Route<dynamic> route, Route<dynamic>? previousRoute, ) { assert(_navigatorListenerRegistration != null); assert(_routesPushedDuringEdit > 0); if (--_routesPushedDuringEdit == 0) { GestureBinding.instance.pointerRouter.addGlobalRoute( _handleGlobalPointerEvent, ); } } void _handleGlobalPointerEvent(PointerEvent event) { assert(_editorController != null); assert(_editorController!.isEditing); assert(_cellsBeingEdited != null); if (event is PointerDownEvent) { final Offset localPosition = globalToLocal(event.position); final TableCellOffset? cellOffset = metrics.getCellAt(localPosition); if (cellOffset == null || !_editorController!.cellsBeingEdited.containsCell(cellOffset)) { _editorController!.save(); } } } void _handleEditFinished( TableViewEditorController controller, TableViewEditOutcome outcome, ) { assert(controller == _editorController); assert(_cellsBeingEdited != null); assert(_navigatorListenerRegistration != null); _initSerialTap(); _navigatorListenerRegistration!.dispose(); _navigatorListenerRegistration = null; markCellsDirty(_cellsBeingEdited!); _cellsBeingEdited = null; GestureBinding.instance.pointerRouter.removeGlobalRoute( _handleGlobalPointerEvent, ); } void _handleRowDisabledFilterChanged(Predicate<int>? previousFilter) { _cancelEditIfNecessary(); markNeedsBuild(); } void _handleSelectionChanged() { // TODO: be more precise about what to rebuild (requires finer grained info from the notification). markNeedsBuild(); } @override @protected void handleSortAdded(TableViewSortController controller, String key) { final int columnIndex = columns.indexWhere( (TableColumn column) => column.key == key, ); _sortedColumns.add(columnIndex); markNeedsBuild(); } @override @protected void handleSortUpdated( TableViewSortController controller, String key, SortDirection? previous, ) { final int columnIndex = columns.indexWhere( (TableColumn column) => column.key == key, ); final SortDirection? direction = controller[key]; if (direction == null) { _sortedColumns.remove(columnIndex); } else { _sortedColumns.add(columnIndex); } markNeedsBuild(); } @override @protected void handleSortChanged(TableViewSortController controller) { _resetSortedColumns(); markNeedsBuild(); } void _onPointerExit(PointerExitEvent event) { if (isHighlightEnabled) { deferMarkNeedsLayout(() { highlightedRow = null; }); } } void _onPointerScroll(PointerScrollEvent event) { if (isHighlightEnabled && event.scrollDelta != Offset.zero) { deferMarkNeedsLayout(() { highlightedRow = null; }); } } void _onPointerHover(PointerHoverEvent event) { if (isHighlightEnabled) { deferMarkNeedsLayout(() { final int rowIndex = metrics.getRowAt(event.localPosition.dy); highlightedRow = rowIndex != -1 && !_isRowDisabled(rowIndex) ? rowIndex : null; }); } } int _selectIndex = -1; void _handleSerialTapUp(SerialTapUpDetails details) { if (details.count == 1) { _handleTap(details.localPosition); } else if (details.count == 2) { _handleDoubleTap(details.localPosition); } } void _handleTap(Offset localPosition) { final TableViewSelectionController? selectionController = this.selectionController; final SelectMode selectMode = selectionController?.selectMode ?? SelectMode.none; if (selectionController != null && selectMode != SelectMode.none) { final int rowIndex = metrics.getRowAt(localPosition.dy); if (rowIndex >= 0 && rowIndex < length && !_isRowDisabled(rowIndex)) { focusNode.requestFocus(); final Set<LogicalKeyboardKey> keys = HardwareKeyboard.instance.logicalKeysPressed; if (isShiftKeyPressed() && selectMode == SelectMode.multi) { final int startIndex = selectionController.firstSelectedIndex; if (startIndex == -1) { selectionController.addSelectedIndex(rowIndex); } else { final int endIndex = selectionController.lastSelectedIndex; final Span range = Span( rowIndex, rowIndex > startIndex ? startIndex : endIndex, ); selectionController.selectedRange = range; } } else if (isPlatformCommandKeyPressed(platform) && selectMode == SelectMode.multi) { if (selectionController.isRowSelected(rowIndex)) { selectionController.removeSelectedIndex(rowIndex); } else { selectionController.addSelectedIndex(rowIndex); } } else if (keys.contains(LogicalKeyboardKey.control) && selectMode == SelectMode.single) { if (selectionController.isRowSelected(rowIndex)) { selectionController.selectedIndex = -1; } else { selectionController.selectedIndex = rowIndex; } } else if (selectMode != SelectMode.none) { if (!selectionController.isRowSelected(rowIndex)) { selectionController.selectedIndex = rowIndex; } _selectIndex = rowIndex; } } } } void _handleDoubleTap(Offset localPosition) { if (isEditingEnabled && !isEditing) { final TableCellOffset? cellOffset = metrics.getCellAt(localPosition); if (cellOffset != null && !_isRowDisabled(cellOffset.rowIndex)) { _editorController!.start(cellOffset.rowIndex, cellOffset.columnIndex); } } if (onDoubleTapRow != null) { final int row = metrics.getRowAt(localPosition.dy); if (row >= 0) { onDoubleTapRow!(row); } } } void _onPointerUp(PointerUpEvent event) { if (_selectIndex != -1 && selectionController!.firstSelectedIndex != selectionController!.lastSelectedIndex) { selectionController!.selectedIndex = _selectIndex; } _selectIndex = -1; } @override MouseCursor get cursor => MouseCursor.defer; @override PointerEnterEventListener? get onEnter => null; @override PointerExitEventListener? get onExit => _onPointerExit; @override bool get validForMouseTracker => isHighlightEnabled; @override void handleEvent(PointerEvent event, BoxHitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (event is PointerDownEvent) { _serialTap?.addPointer(event); } else if (event is PointerHoverEvent) { return _onPointerHover(event); } else if (event is PointerScrollEvent) { return _onPointerScroll(event); } else if (event is PointerExitEvent) { return _onPointerExit(event); } else if (event is PointerUpEvent) { return _onPointerUp(event); } super.handleEvent(event, entry); } @override void attach(PipelineOwner owner) { super.attach(owner); _initSerialTap(); if (_selectionController != null) { _selectionController!.attach(this); } if (_editorController != null) { _editorController!.attach(this); } focusNode.addListener(_handleFocusChange); } @override void detach() { _disposeSerialTap(); if (_selectionController != null) { _selectionController!.detach(); } if (_editorController != null) { _editorController!.detach(); } if (_cellsBeingEdited != null) { assert(_editorController != null); _handleEditFinished(_editorController!, TableViewEditOutcome.canceled); } focusNode.removeListener(_handleFocusChange); super.detach(); } @override void paint(PaintingContext context, Offset offset) { if (_sortedColumns.isNotEmpty) { final Paint paint = Paint() ..style = PaintingStyle.fill ..color = const Color(0xfff7f5ed); for (int columnIndex in _sortedColumns) { final Rect columnBounds = metrics.getColumnBounds(columnIndex); context.canvas.drawRect(columnBounds.shift(offset), paint); } } if (_highlightedRow != null) { final Rect rowBounds = metrics.getRowBounds(_highlightedRow!); final Paint paint = Paint() ..style = PaintingStyle.fill ..color = const Color(0xffdddcd5); context.canvas.drawRect(rowBounds.shift(offset), paint); } if (selectionController != null && selectionController!.selectedRanges.isNotEmpty) { final Paint paint = Paint() ..style = PaintingStyle.fill ..color = focusNode.hasFocus ? const Color(0xff14538b) : const Color(0xffc4c3bc); for (Span range in selectionController!.selectedRanges) { Rect bounds = metrics.getRowBounds(range.start); bounds = bounds.expandToInclude(metrics.getRowBounds(range.end)); context.canvas.drawRect(bounds.shift(offset), paint); } } super.paint(context, offset); } } class TableViewHeader extends RenderObjectWidget { const TableViewHeader({ Key? key, required this.rowHeight, required this.columns, this.roundColumnWidthsToWholePixel = false, this.metricsController, this.sortController, }) : super(key: key); final double rowHeight; final List<TableColumn> columns; final bool roundColumnWidthsToWholePixel; final TableViewMetricsController? metricsController; final TableViewSortController? sortController; @override TableViewHeaderElement createElement() => TableViewHeaderElement(this); @override RenderTableViewHeader createRenderObject(BuildContext context) { return RenderTableViewHeader( rowHeight: rowHeight, columns: columns, roundColumnWidthsToWholePixel: roundColumnWidthsToWholePixel, metricsController: metricsController, sortController: sortController, ); } @override void updateRenderObject( BuildContext context, RenderTableViewHeader renderObject, ) { renderObject ..rowHeight = rowHeight ..columns = columns ..roundColumnWidthsToWholePixel = roundColumnWidthsToWholePixel ..metricsController = metricsController ..sortController = sortController; } @protected Widget renderHeaderEnvelope({ BuildContext? context, required int columnIndex, }) { return TableViewHeaderEnvelope( column: columns[columnIndex], columnIndex: columnIndex, sortController: sortController, ); } } class TableViewHeaderEnvelope extends StatefulWidget { const TableViewHeaderEnvelope({ required this.column, required this.columnIndex, this.sortController, Key? key, }) : super(key: key); final TableColumn column; final int columnIndex; final TableViewSortController? sortController; @override _TableViewHeaderEnvelopeState createState() => _TableViewHeaderEnvelopeState(); } class _TableViewHeaderEnvelopeState extends State<TableViewHeaderEnvelope> { bool _pressed = false; static const List<Color> _defaultGradientColors = <Color>[ Color(0xffdfded7), Color(0xfff6f4ed), ]; static const List<Color> _pressedGradientColors = <Color>[ Color(0xffdbdad3), Color(0xffc4c3bc), ]; @override Widget build(BuildContext context) { final bool isColumnResizable = widget.column.width is ConstrainedTableColumnWidth; Widget renderedHeader = Padding( padding: EdgeInsets.only(left: 3), // TODO: better error than "Null check operator used on a null" when headerBuilder is null child: widget.column.headerBuilder!(context, widget.columnIndex), ); if (widget.sortController != null && widget.sortController!.sortMode != TableViewSortMode.none) { renderedHeader = GestureDetector( onTapDown: (TapDownDetails _) => setState(() => _pressed = true), onTapUp: (TapUpDetails _) => setState(() => _pressed = false), onTapCancel: () => setState(() => _pressed = false), onTap: () { final String key = widget.column.key; SortDirection? direction = widget.sortController![key]; switch (direction) { case SortDirection.ascending: direction = SortDirection.descending; break; default: direction = SortDirection.ascending; break; } if (widget.sortController!.sortMode == TableViewSortMode.singleColumn) { widget.sortController![key] = direction; } else if (isShiftKeyPressed()) { widget.sortController![key] = direction; } else { widget.sortController!.replaceAll(<String, SortDirection>{ key: direction, }); } }, child: renderedHeader, ); } return DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: _pressed ? _pressedGradientColors : _defaultGradientColors, ), border: Border( bottom: const BorderSide(color: const Color(0xff999999)), ), ), child: Row( children: [ Expanded(child: renderedHeader), // TODO: fixed-width column should still paint dividers, but they aren't if (isColumnResizable) SizedBox( width: _kResizeHandleTargetPixels, child: DecoratedBox( decoration: BoxDecoration( border: Border( right: const BorderSide(color: const Color(0xff999999)), ), ), child: MouseRegion( cursor: SystemMouseCursors.resizeLeftRight, child: GestureDetector( key: Key('$this dividerKey ${widget.columnIndex}'), behavior: HitTestBehavior.translucent, dragStartBehavior: DragStartBehavior.down, onHorizontalDragUpdate: (DragUpdateDetails details) { assert( widget.column.width is ConstrainedTableColumnWidth, ); final ConstrainedTableColumnWidth width = widget.column.width as ConstrainedTableColumnWidth; final newWidth = width.width + details.primaryDelta!; if (newWidth > _kResizeHandleTargetPixels) { widget.column.width = width.copyWith(width: newWidth); } }, ), ), ), ), ], ), ); } } @visibleForTesting class TableViewHeaderElement extends RenderObjectElement with TableViewElementMixin { TableViewHeaderElement(TableViewHeader tableView) : super(tableView); @override TableViewHeader get widget => super.widget as TableViewHeader; @override RenderTableViewHeader get renderObject => super.renderObject as RenderTableViewHeader; @override @protected Widget renderCell(int rowIndex, int columnIndex) { return widget.renderHeaderEnvelope(context: this, columnIndex: columnIndex); } @override @protected Widget? buildPrototypeCell(int columnIndex) { final TableColumn column = widget.columns[columnIndex]; return column.prototypeCellBuilder != null ? column.prototypeCellBuilder!(this) : null; } } class RenderTableViewHeader extends RenderSegment with RenderTableViewMixin, TableViewColumnListenerMixin, TableViewSortingMixin { RenderTableViewHeader({ required double rowHeight, required List<TableColumn> columns, bool roundColumnWidthsToWholePixel = false, TableViewMetricsController? metricsController, TableViewSortController? sortController, }) { initializeSortListener(); this.length = 1; this.rowHeight = rowHeight; this.columns = columns; this.roundColumnWidthsToWholePixel = roundColumnWidthsToWholePixel; this.metricsController = metricsController; this.sortController = sortController; } @override @protected void handleSortAdded(TableViewSortController _, String __) { markNeedsPaint(); } @override @protected void handleSortUpdated( TableViewSortController _, String __, SortDirection? ___, ) { markNeedsPaint(); } @override @protected void handleSortChanged(TableViewSortController _) { markNeedsPaint(); } @override void paint(PaintingContext context, Offset offset) { super.paint(context, offset); if (sortController != null) { for (int columnIndex = 0; columnIndex < columns.length; columnIndex++) { final SortDirection? sortDirection = sortController![columns[columnIndex].key]; if (sortDirection != null) { final Rect cellBounds = metrics.getCellBounds(0, columnIndex); final SortIndicatorPainter painter = SortIndicatorPainter( sortDirection: sortDirection, ); context.canvas.save(); try { const Size indicatorSize = Size(7, 4); context.canvas.translate( cellBounds.right - indicatorSize.width - 5, cellBounds.centerRight.dy - indicatorSize.height / 2, ); painter.paint(context.canvas, indicatorSize); } finally { context.canvas.restore(); } } } } } } mixin TableViewColumnListenerMixin on RenderTableViewMixin { List<TableColumn>? _columns; @override List<TableColumn>? get rawColumns => _columns; @override List<TableColumn> get columns => _columns!; @override set columns(List<TableColumn> value) { if (_columns == value) return; final List<TableColumn>? oldColumns = _columns; _columns = value; markNeedsMetrics(); markNeedsBuild(); if (oldColumns != null) { for (int i = 0; i < oldColumns.length; i++) { oldColumns[i].removeListener(_columnListeners[i]); } } _columnListeners = <VoidCallback>[]; for (int i = 0; i < value.length; i++) { final VoidCallback listener = _listenerForColumn(i); _columnListeners.add(listener); value[i].addListener(listener); } } late List<VoidCallback> _columnListeners; VoidCallback _listenerForColumn(int columnIndex) { return () { final Rect viewport = constraints.viewportResolver.resolve(size); markCellsDirty( TableCellRect.fromLTRB( columnIndex, viewport.top ~/ rowHeight, columnIndex, viewport.bottom ~/ rowHeight, ), ); markNeedsMetrics(); }; } } mixin TableViewSortingMixin on RenderTableViewMixin { late TableViewSortListener _sortListener; TableViewSortController? _sortController; TableViewSortController? get sortController => _sortController; set sortController(TableViewSortController? value) { if (_sortController == value) return; if (_sortController != null) { _sortController!.removeListener(_sortListener); } _sortController = value; if (_sortController != null) { _sortController!.addListener(_sortListener); } markNeedsBuild(); } @protected void initializeSortListener() { _sortListener = TableViewSortListener( onAdded: handleSortAdded, onUpdated: handleSortUpdated, onChanged: handleSortChanged, ); } @protected void handleSortAdded(TableViewSortController controller, String key) {} @protected void handleSortUpdated( TableViewSortController controller, String key, SortDirection? previous, ) {} @protected void handleSortChanged(TableViewSortController controller) {} }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/text_input.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/material.dart' show InputBorder, InputDecoration, OutlineInputBorder, TextField; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'foundation.dart'; class TextInput extends StatefulWidget { const TextInput({ Key? key, this.controller, this.onKeyEvent, this.onTextUpdated, this.validator, this.focusNode, this.backgroundColor = const Color(0xffffffff), this.obscureText = false, this.autofocus = false, this.enabled = true, }) : super(key: key); final TextEditingController? controller; final ValueChanged<KeyEvent>? onKeyEvent; final ValueChanged<String>? onTextUpdated; final Predicate<String>? validator; final FocusNode? focusNode; final Color backgroundColor; final bool obscureText; final bool autofocus; final bool enabled; @override _TextInputState createState() => _TextInputState(); } class _TextInputState extends State<TextInput> { FocusNode? _focusNode; TextEditingController? _controller; late TextEditingValue _lastValidValue; static const InputBorder _inputBorder = OutlineInputBorder( borderSide: BorderSide(color: Color(0xff999999)), borderRadius: BorderRadius.zero, ); static const Color _disabledBackgroundColor = Color(0xffdddcd5); FocusNode get focusNode => widget.focusNode ?? _focusNode!; TextEditingController get controller => widget.controller ?? _controller!; void _handleEdit() { final String text = controller.text; if (text == _lastValidValue.text) { _lastValidValue = controller.value; } else if (widget.validator == null) { _lastValidValue = controller.value; if (widget.onTextUpdated != null) widget.onTextUpdated!(text); } else if (widget.validator!(text)) { _lastValidValue = controller.value; if (widget.onTextUpdated != null) widget.onTextUpdated!(text); } else { controller.value = _lastValidValue; SystemSound.play(SystemSoundType.alert); } } @override void initState() { super.initState(); if (widget.focusNode == null) { _focusNode = FocusNode(); } if (widget.controller == null) { _controller = TextEditingController(); } controller.addListener(_handleEdit); _lastValidValue = controller.value; if (widget.autofocus) { SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { if (mounted) { focusNode.requestFocus(); } }); } } @override void didUpdateWidget(covariant TextInput oldWidget) { super.didUpdateWidget(oldWidget); if (widget.focusNode != oldWidget.focusNode) { if (widget.focusNode == null) { assert(_focusNode == null); _focusNode = FocusNode(); } else if (oldWidget.focusNode == null) { assert(_focusNode != null); _focusNode!.dispose(); _focusNode = null; } } if (widget.controller != oldWidget.controller) { if (widget.controller == null) { assert(_controller == null); oldWidget.controller!.removeListener(_handleEdit); _controller = TextEditingController(); _controller!.addListener(_handleEdit); } else if (oldWidget.controller == null) { assert(_controller != null); _controller!.removeListener(_handleEdit); _controller!.dispose(); _controller = null; widget.controller!.addListener(_handleEdit); } else { oldWidget.controller!.removeListener(_handleEdit); widget.controller!.addListener(_handleEdit); } } } @override void dispose() { _focusNode?.dispose(); _controller?.removeListener(_handleEdit); _controller?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { Widget result = TextField( controller: controller, focusNode: widget.onKeyEvent == null ? focusNode : null, cursorWidth: 1, obscureText: widget.obscureText, enabled: widget.enabled, cursorColor: const Color(0xff000000), style: const TextStyle(fontFamily: 'Verdana', fontSize: 11), decoration: InputDecoration( fillColor: widget.enabled ? widget.backgroundColor : _disabledBackgroundColor, hoverColor: widget.backgroundColor, filled: true, contentPadding: const EdgeInsets.fromLTRB(3, 13, 0, 4), isDense: true, enabledBorder: _inputBorder, focusedBorder: _inputBorder, disabledBorder: _inputBorder, ), ); if (widget.onKeyEvent != null) { result = KeyboardListener( focusNode: focusNode, onKeyEvent: widget.onKeyEvent, child: result, ); } return result; } }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/visibility_aware.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; // TODO: eliminate the need for a tree walk when visibility changes mixin VisibilityAwareMixin on RenderBox { Set<int> _hiddenAncestors = <int>{}; bool _isVisible = true; bool get isVisible => _isVisible && _hiddenAncestors.isEmpty; set isVisible(bool value) { if (value != _isVisible) { bool wasVisible = isVisible; _isVisible = value; visitChildren(_setHiddenAncestorsField(value, depth)); if (isVisible != wasVisible) { handleIsVisibleChanged(); } } } static void setChildVisible(RenderObject child, bool isVisible) { if (child is VisibilityAwareMixin) { child.isVisible = isVisible; } else { child.visitChildren(_setHiddenAncestorsField(isVisible, child.depth)); } } static RenderObjectVisitor _setHiddenAncestorsField( bool isVisible, int depth, ) { return isVisible ? _unhideDescendants(depth) : _hideDescendants(depth); } static RenderObjectVisitor _hideDescendants(int depth) { void visitor(RenderObject child) { if (child is VisibilityAwareMixin) { bool childWasVisible = child.isVisible; child._hiddenAncestors.add(depth); if (child.isVisible != childWasVisible) { child.handleIsVisibleChanged(); } } child.visitChildren(visitor); } return visitor; } static RenderObjectVisitor _unhideDescendants(int depth) { void visitor(RenderObject child) { if (child is VisibilityAwareMixin) { bool childWasVisible = child.isVisible; child._hiddenAncestors.remove(depth); if (child.isVisible != childWasVisible) { child.handleIsVisibleChanged(); } } child.visitChildren(visitor); } return visitor; } @protected void handleIsVisibleChanged() {} }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
lib/src/widget_surveyor.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; /// Class that allows callers to measure the size of arbitrary widgets when /// laid out with specific constraints. /// /// The widget surveyor creates synthetic widget trees to hold the widgets it /// measures. This is important because if the widgets (or any widgets in their /// subtrees) depend on any inherited widgets (e.g. [Directionality]) that they /// assume exist in their ancestry, those assumptions may hold true when the /// widget is rendered by the application but prove false when the widget is /// rendered via the widget surveyor. Due to this, callers are advised to /// either: /// /// 1. pass in widgets that don't depend on inherited widgets, or /// 1. ensure all inherited widget dependencies exist in the widget tree /// that's passed to the widget surveyor's measure methods. class WidgetSurveyor { const WidgetSurveyor(); /// Builds a widget from the specified builder, inserts the widget into a /// synthetic widget tree, lays out the resulting render tree, and returns /// the size of the laid-out render tree. /// /// The build context that's passed to the `builder` argument will represent /// the root of the synthetic tree. /// /// The `constraints` argument specify the constraints that will be passed /// to the render tree during layout. If unspecified, the widget will be laid /// out unconstrained. Size measureBuilder( WidgetBuilder builder, { BoxConstraints constraints = const BoxConstraints(), }) { return measureWidget(Builder(builder: builder), constraints: constraints); } /// Inserts the specified widget into a synthetic widget tree, lays out the /// resulting render tree, and returns the size of the laid-out render tree. /// /// The `constraints` argument specify the constraints that will be passed /// to the render tree during layout. If unspecified, the widget will be laid /// out unconstrained. Size measureWidget( Widget widget, { BoxConstraints constraints = const BoxConstraints(), }) { final SurveyorView rendered = _render(widget, constraints); assert(rendered.hasSize); return rendered.size; } double measureDistanceToBaseline( Widget widget, { TextBaseline baseline = TextBaseline.alphabetic, BoxConstraints constraints = const BoxConstraints(), }) { final SurveyorView rendered = _render( widget, constraints, baselineToCalculate: baseline, ); return rendered.childBaseline ?? rendered.size.height; } double? measureDistanceToActualBaseline( Widget widget, { TextBaseline baseline = TextBaseline.alphabetic, BoxConstraints constraints = const BoxConstraints(), }) { final SurveyorView rendered = _render( widget, constraints, baselineToCalculate: baseline, ); return rendered.childBaseline; } SurveyorView _render( Widget widget, BoxConstraints constraints, { TextBaseline? baselineToCalculate, }) { bool debugIsPerformingCleanup = false; final PipelineOwner pipelineOwner = PipelineOwner( onNeedVisualUpdate: () { assert(() { if (!debugIsPerformingCleanup) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('Visual update was requested during survey.'), ErrorDescription( 'WidgetSurveyor does not support a render object ' 'calling markNeedsLayout(), markNeedsPaint(), or ' 'markNeedsSemanticUpdate() while the widget is being surveyed.', ), ]); } return true; }()); }, ); final SurveyorView rootView = pipelineOwner.rootNode = SurveyorView(); final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager()); assert(buildOwner.globalKeyCount == 0); final RenderObjectToWidgetElement element = RenderObjectToWidgetAdapter<RenderBox>( container: rootView, debugShortDescription: '[root]', child: widget, ).attachToRenderTree(buildOwner); try { rootView.baselineToCalculate = baselineToCalculate; rootView.childConstraints = constraints; rootView.scheduleInitialLayout(); pipelineOwner.flushLayout(); assert(rootView.child != null); return rootView; } finally { // Un-mount all child elements to properly clean up. debugIsPerformingCleanup = true; try { element.update( RenderObjectToWidgetAdapter<RenderBox>(container: rootView), ); buildOwner.finalizeTree(); } finally { debugIsPerformingCleanup = false; } assert( buildOwner.globalKeyCount == 1, ); // RenderObjectToWidgetAdapter uses a global key } } } class SurveyorView extends RenderBox with RenderObjectWithChildMixin<RenderBox> { BoxConstraints? childConstraints; TextBaseline? baselineToCalculate; double? childBaseline; @override void performLayout() { assert(child != null); assert(childConstraints != null); child!.layout(childConstraints!, parentUsesSize: true); if (baselineToCalculate != null) { childBaseline = child!.getDistanceToBaseline(baselineToCalculate!); } size = child!.size; } @override void debugAssertDoesMeetConstraints() => true; }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/activity_indicator_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:ui' as ui; import 'package:chicago/chicago.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('ActivityIndicator smoke test', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: ActivityIndicator(), ), ); expect(find.byType(ActivityIndicator), findsOneWidget); }); testWidgets('ActivityIndicator animates', (WidgetTester tester) async { final repaintBoundaryKey = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RepaintBoundary( key: repaintBoundaryKey, child: const ActivityIndicator(), ), ), ); final RenderRepaintBoundary renderRepaintBoundary = repaintBoundaryKey.currentContext!.findRenderObject()! as RenderRepaintBoundary; final bytes1 = await tester.runAsync(() async { final image = await renderRepaintBoundary.toImage(); return image.toByteData(format: ui.ImageByteFormat.png); }); await tester.pump(const Duration(milliseconds: 100)); final bytes2 = await tester.runAsync(() async { final image = await renderRepaintBoundary.toImage(); return image.toByteData(format: ui.ImageByteFormat.png); }); expect( bytes1!.buffer.asUint8List(), isNot(equals(bytes2!.buffer.asUint8List())), ); }); testWidgets('ActivityIndicator has semantic label', ( WidgetTester tester, ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: ActivityIndicator(semanticLabel: 'Loading...'), ), ); expect(find.bySemanticsLabel('Loading...'), findsOneWidget); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/basic_list_view_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('BasicListView smoke test', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 200, height: 200, child: ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.stretch, view: BasicListView( length: 10, itemHeight: 20, itemBuilder: (context, index) => Text('Item $index'), ), ), ), ), ); expect(find.byType(BasicListView), findsOneWidget); expect(find.text('Item 0').hitTestable(), findsOneWidget); expect(find.text('Item 9').hitTestable(), findsOneWidget); }); testWidgets('BasicListView empty list', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 200, height: 200, child: ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.stretch, view: BasicListView( length: 0, itemHeight: 20, itemBuilder: (context, index) => Text('Item $index'), ), ), ), ), ); expect(find.byType(BasicListView), findsOneWidget); expect(find.byType(Text), findsNothing); }); testWidgets('BUG: BasicListView can scroll', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( height: 99, width: 200, child: ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.stretch, view: BasicListView( length: 20, itemHeight: 20, itemBuilder: (context, index) => Text('Item $index'), ), ), ), ), ); // This test will likely fail because of the underlying culling bug, // but is included for completeness. expect(find.text('Item 5').hitTestable(), findsNothing); }, skip: true); testWidgets('BUG: BasicListView builds items outside the viewport', ( WidgetTester tester, ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( height: 99, width: 200, child: ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.stretch, view: BasicListView( length: 20, itemHeight: 20, itemBuilder: (context, index) => Text('Item $index'), ), ), ), ), ); final RenderBasicListView renderObject = tester.renderObject( find.byType(BasicListView), ); final List<int> builtItems = <int>[]; renderObject.visitChildren((child) { final parentData = child.parentData as ListViewParentData; builtItems.add(parentData.index); }); builtItems.sort(); // This assertion is expected to fail, proving the bug. // It will likely find that items 0-5 are built, when it should only be 0-4. expect(builtItems, orderedEquals([0, 1, 2, 3, 4])); }, skip: true); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/border_pane_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('BorderPane smoke test', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: BorderPane(child: Text('Test Content')), ), ); expect(find.byType(BorderPane), findsOneWidget); expect(find.text('Test Content'), findsOneWidget); }); testWidgets('BorderPane with title', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: BorderPane(title: 'Test Title', child: Text('Test Content')), ), ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Test Content'), findsOneWidget); }); testWidgets('BorderPane title position (LTR)', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: BorderPane( title: 'Test Title', inset: 20, child: Container(width: 200, height: 200), ), ), ); final Offset titlePosition = tester.getTopLeft(find.text('Test Title')); expect(titlePosition.dx, 20); }); testWidgets('BorderPane title position (RTL)', (WidgetTester tester) async { await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: Directionality( textDirection: TextDirection.rtl, child: SizedBox( width: 300, child: BorderPane( title: 'Test Title', inset: 20, child: Container(width: 200, height: 200), ), ), ), ), ); final Offset titlePosition = tester.getTopRight(find.text('Test Title')); // Total width is 300, inset is 20 from the right edge. expect(titlePosition.dx, 300 - 20); }); testWidgets('BorderPane child position', (WidgetTester tester) async { const double borderThickness = 1.0; await tester.pumpWidget( const Align( alignment: Alignment.topLeft, child: Directionality( textDirection: TextDirection.ltr, child: BorderPane( title: 'Test Title', borderThickness: borderThickness, child: SizedBox(key: ValueKey('child'), width: 200, height: 200), ), ), ), ); // Get the actual height of the title widget. final double titleHeight = tester.getSize(find.text('Test Title')).height; // Calculate the expected offset of the outer container. final double expectedBoxDy = (titleHeight / 2).roundToDouble(); // Get the actual position of the inner child. final Offset childPosition = tester.getTopLeft( find.byKey(const ValueKey('child')), ); // The child's final position is the container's offset plus the border padding. expect(childPosition.dy, expectedBoxDy + borderThickness); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/calendar_button_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('CalendarButton smoke test', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp(home: Scaffold(body: Center(child: CalendarButton()))), ); expect(find.byType(CalendarButton), findsOneWidget); }); testWidgets('CalendarButton shows initial date', (WidgetTester tester) async { final date = const CalendarDate(2023, 4, 15); // May 15, 2023 await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center(child: CalendarButton(initialSelectedDate: date)), ), ), ); expect(find.text('May 16, 2023'), findsOneWidget); }); testWidgets('Tapping button opens calendar popup', ( WidgetTester tester, ) async { await tester.pumpWidget( const MaterialApp(home: Scaffold(body: Center(child: CalendarButton()))), ); expect(find.byType(Calendar), findsNothing); await tester.tap(find.byType(CalendarButton)); await tester.pumpAndSettle(); // Wait for popup animation expect(find.byType(Calendar), findsOneWidget); }); testWidgets('Selecting a date in popup updates button', ( WidgetTester tester, ) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Center( child: CalendarButton( initialYear: 2023, initialMonth: 4, // May ), ), ), ), ); await tester.tap(find.byType(CalendarButton)); await tester.pumpAndSettle(); expect(find.byType(Calendar), findsOneWidget); expect(find.text('May 21, 2023'), findsNothing); await tester.tap(find.text('21')); await tester.pumpAndSettle(); expect(find.byType(Calendar), findsNothing); // Popup should be closed expect( find.text('May 21, 2023'), findsOneWidget, ); // Button text should be updated }); testWidgets('onDateChanged callback is invoked', (WidgetTester tester) async { CalendarDate? selectedDate; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: CalendarButton( initialYear: 2023, initialMonth: 4, // May onDateChanged: (date) => selectedDate = date, ), ), ), ), ); await tester.tap(find.byType(CalendarButton)); await tester.pumpAndSettle(); await tester.tap(find.text('21')); await tester.pumpAndSettle(); expect(selectedDate, const CalendarDate(2023, 4, 20)); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/calendar_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Calendar smoke test', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Calendar( initialYear: 2023, initialMonth: 8, // September ), ), ); expect(find.byType(Calendar), findsOneWidget); expect(find.text('September'), findsOneWidget); expect(find.text('2023'), findsOneWidget); }); testWidgets('Can select a date', (WidgetTester tester) async { final CalendarSelectionController controller = CalendarSelectionController(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Calendar( initialYear: 2023, initialMonth: 8, // September selectionController: controller, ), ), ); await tester.tap(find.text('15')); await tester.pump(); expect( controller.value, const CalendarDate(2023, 8, 14), ); // Day is 0-indexed }); testWidgets('onDateChanged callback is invoked', (WidgetTester tester) async { CalendarDate? selectedDate; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Calendar( initialYear: 2023, initialMonth: 8, // September onDateChanged: (date) => selectedDate = date, ), ), ); await tester.tap(find.text('21')); await tester.pump(); expect(selectedDate, const CalendarDate(2023, 8, 20)); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/checkbox_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Checkbox smoke test', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Checkbox(trailing: const Text('Test')), ), ); expect(find.byType(Checkbox), findsOneWidget); expect(find.text('Test'), findsOneWidget); }); testWidgets('Can check and uncheck', (WidgetTester tester) async { final CheckboxController controller = CheckboxController.simple(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Checkbox(controller: controller), ), ); expect(controller.checked, isFalse); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(controller.checked, isTrue); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(controller.checked, isFalse); }); testWidgets('onChange callback is invoked', (WidgetTester tester) async { int callCount = 0; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Checkbox(onChange: () => callCount++), ), ); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(callCount, 1); }); testWidgets('Tri-state checkbox cycles through states', ( WidgetTester tester, ) async { final CheckboxController controller = CheckboxController.triState( canUserToggleMixed: true, ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Checkbox(controller: controller), ), ); expect(controller.state, CheckboxState.unchecked); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(controller.state, CheckboxState.mixed); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(controller.state, CheckboxState.checked); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(controller.state, CheckboxState.unchecked); }); testWidgets('Checkbox is disabled', (WidgetTester tester) async { final CheckboxController controller = CheckboxController.simple(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Checkbox(controller: controller, isEnabled: false), ), ); expect(controller.checked, isFalse); await tester.tap(find.byType(Checkbox)); await tester.pump(); expect(controller.checked, isFalse); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/colors_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/src/colors.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('brighten', () { test('should increase the brightness value', () { const Color color = Color(0xff808080); // HSV value is 0.5 final Color brightened = brighten(color); final HSVColor hsv = HSVColor.fromColor(brightened); // Expecting value to be 0.5 + 0.1 = 0.6 expect(hsv.value, closeTo(0.6, 0.01)); }); test('should not exceed a brightness value of 1.0', () { const Color color = Color(0xffffffff); // HSV value is 1.0 final Color brightened = brighten(color); final HSVColor hsv = HSVColor.fromColor(brightened); expect(hsv.value, 1.0); }); }); group('darken', () { test('should decrease the brightness value', () { const Color color = Color(0xff808080); // HSV value is 0.5 final Color darkened = darken(color); final HSVColor hsv = HSVColor.fromColor(darkened); // Expecting value to be 0.5 - 0.1 = 0.4 expect(hsv.value, closeTo(0.4, 0.01)); }); test('should not go below a brightness value of 0.0', () { const Color color = Color(0xff000000); // HSV value is 0.0 final Color darkened = darken(color); final HSVColor hsv = HSVColor.fromColor(darkened); expect(hsv.value, 0.0); }); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/indexed_offset_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('operator ==', () { expect(IndexedOffset(0, 0), equals(IndexedOffset(0, 0))); expect(IndexedOffset(3, 7), equals(IndexedOffset(3, 7))); expect(IndexedOffset(0, 0), isNot(equals(IndexedOffset(1, 1)))); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/list_button_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:io' as io show Platform; import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart' hide TableCell, TableRow; import 'package:flutter_test/flutter_test.dart'; const String kShortString = 'Short'; const String kLongString = 'Very Very Very Long'; const String kPlaceholderString = '-'; const double kAhemGlyphEmSize = 14; const Size kShortStringSize = Size( kAhemGlyphEmSize * kShortString.length, kAhemGlyphEmSize, ); const Size kLongStringSize = Size( kAhemGlyphEmSize * kLongString.length, kAhemGlyphEmSize, ); const Size kPlaceholderStringSize = Size( kAhemGlyphEmSize * kPlaceholderString.length, kAhemGlyphEmSize, ); const EdgeInsets kContentPadding = EdgeInsets.symmetric( horizontal: 5, vertical: 2, ); const EdgeInsets kBorder = EdgeInsets.all(1); const double kPulldownWidth = 15; const double kDividerWidth = 1; const double kMinHeight = 20; final Offset kNonContentBounds = Offset( kContentPadding.horizontal + kBorder.horizontal + kPulldownWidth + kDividerWidth, kContentPadding.vertical + kBorder.vertical, ); class TypeLiteral<T> { Type get type => T; } Widget buildItem( BuildContext context, String? item, bool isForMeasurementOnly, ) { final TextStyle style = DefaultTextStyle.of(context).style; final TextDirection textDirection = Directionality.of(context); return Text( item ?? kPlaceholderString, maxLines: 1, softWrap: false, textDirection: textDirection, style: style, ); } void main() { late ListViewSelectionController selectionController; setUp(() { selectionController = ListViewSelectionController(); }); Widget buildListButtonScaffold({ ListButtonWidth width = ListButtonWidth.shrinkWrapCurrentItem, BoxConstraints? constraints, }) { Widget result = RepaintBoundary( child: ListButton<String>( width: width, items: <String>[kShortString, kLongString], builder: buildItem, selectionController: selectionController, ), ); if (constraints != null) { result = ConstrainedBox(constraints: constraints, child: result); } return Directionality( textDirection: TextDirection.ltr, child: UnconstrainedBox(child: result), ); } testWidgets('Produces correct pixels', (WidgetTester tester) async { selectionController.selectedIndex = 1; await tester.pumpWidget(buildListButtonScaffold()); await expectLater( find.byType(TypeLiteral<ListButton<String>>().type), matchesGoldenFile('list_button_test.golden.png'), ); }, skip: !io.Platform.isMacOS); testWidgets('Only builds currently selected item', ( WidgetTester tester, ) async { await tester.pumpWidget(buildListButtonScaffold()); expect(find.text(kShortString), findsNothing); expect(find.text(kLongString), findsNothing); expect(find.text(kPlaceholderString), findsOneWidget); selectionController.selectedIndex = 0; await tester.pump(); expect(find.text(kShortString), findsOneWidget); expect(find.text(kLongString), findsNothing); expect(find.text(kPlaceholderString), findsNothing); selectionController.selectedIndex = 1; await tester.pump(); expect(find.text(kShortString), findsNothing); expect(find.text(kLongString), findsOneWidget); expect(find.text(kPlaceholderString), findsNothing); }); testWidgets( 'ListButtonWidth.shrinkWrapAllItems sets correct width with unbounded constraints', (WidgetTester tester) async { await tester.pumpWidget( buildListButtonScaffold(width: ListButtonWidth.shrinkWrapAllItems), ); expect(tester.getSize(find.text(kPlaceholderString)), kLongStringSize); selectionController.selectedIndex = 0; await tester.pump(); expect(tester.getSize(find.text(kShortString)), kLongStringSize); selectionController.selectedIndex = 1; await tester.pump(); expect(tester.getSize(find.text(kLongString)), kLongStringSize); }, ); testWidgets( 'ListButtonWidth.shrinkWrapAllItems renders correctly with bounded constraints', (WidgetTester tester) async { await tester.pumpWidget( buildListButtonScaffold( width: ListButtonWidth.shrinkWrapAllItems, constraints: BoxConstraints( minWidth: kLongStringSize.width / 2, maxWidth: kLongStringSize.width + 50, ), ), ); expect(tester.getSize(find.text(kPlaceholderString)), kLongStringSize); expect( tester.getSize(find.byType(TypeLiteral<ListButton<String>>().type)), kLongStringSize + kNonContentBounds, ); }, ); testWidgets( 'ListButtonWidth.shrinkWrapAllItems grows content when required', (WidgetTester tester) async { await tester.pumpWidget( buildListButtonScaffold( width: ListButtonWidth.shrinkWrapAllItems, constraints: BoxConstraints(minWidth: kLongStringSize.width + 50), ), ); final Size expectedListButtonSize = kLongStringSize + Offset(50, kNonContentBounds.dy); expect( tester.getSize(find.text(kPlaceholderString)), expectedListButtonSize - kNonContentBounds, ); expect( tester.getSize(find.byType(TypeLiteral<ListButton<String>>().type)), expectedListButtonSize, ); }, ); testWidgets( 'ListButtonWidth.shrinkWrapAllItems shrinks content when required', (WidgetTester tester) async { await tester.pumpWidget( buildListButtonScaffold( width: ListButtonWidth.shrinkWrapAllItems, constraints: BoxConstraints(maxWidth: kShortStringSize.width), ), ); final Size expectedListButtonSize = kShortStringSize + Offset(0, kNonContentBounds.dy); expect( tester.getSize(find.text(kPlaceholderString)), expectedListButtonSize - kNonContentBounds, ); expect( tester.getSize(find.byType(TypeLiteral<ListButton<String>>().type)), expectedListButtonSize, ); }, ); testWidgets( 'ListButtonWidth.shrinkWrapCurrentItem sets correct width with unbounded constraints', (WidgetTester tester) async { await tester.pumpWidget( buildListButtonScaffold(width: ListButtonWidth.shrinkWrapCurrentItem), ); expect( tester.getSize(find.text(kPlaceholderString)), kPlaceholderStringSize, ); selectionController.selectedIndex = 0; await tester.pump(); expect(tester.getSize(find.text(kShortString)), kShortStringSize); selectionController.selectedIndex = 1; await tester.pump(); expect(tester.getSize(find.text(kLongString)), kLongStringSize); }, ); testWidgets('ListButtonWidth.expand sets expanded width', ( WidgetTester tester, ) async { await tester.pumpWidget( buildListButtonScaffold( width: ListButtonWidth.expand, constraints: BoxConstraints(maxWidth: 500), ), ); final Size expectedListButtonSize = Size( 500, kAhemGlyphEmSize + kNonContentBounds.dy, ); final Size expectedContentSize = expectedListButtonSize - kNonContentBounds as Size; expect(tester.getSize(find.text(kPlaceholderString)), expectedContentSize); selectionController.selectedIndex = 0; await tester.pump(); expect(tester.getSize(find.text(kShortString)), expectedContentSize); selectionController.selectedIndex = 1; await tester.pump(); expect(tester.getSize(find.text(kLongString)), expectedContentSize); }); testWidgets('ListButtonWidth.expand fails with unbounded with', ( WidgetTester tester, ) async { await tester.pumpWidget( buildListButtonScaffold(width: ListButtonWidth.expand), ); expect(tester.takeException(), isFlutterError); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/list_view_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart' hide ListView, TableCell, TableRow; import 'package:flutter_test/flutter_test.dart'; void main() { Widget buildDummy( BuildContext context, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { return Container(); } Widget wrap(Widget widget) { return ScrollPane( horizontalScrollBarPolicy: ScrollBarPolicy.stretch, verticalScrollBarPolicy: ScrollBarPolicy.stretch, view: widget, ); } // Regression test for https://github.com/tvolkert/chicago/issues/10 testWidgets('Can reuse selectionController across render objects', ( WidgetTester tester, ) async { final ListViewSelectionController controller = ListViewSelectionController(); await tester.pumpWidget( wrap( ListView( selectionController: controller, itemHeight: 20, length: 1, itemBuilder: buildDummy, ), ), ); await tester.pumpWidget( Padding( padding: EdgeInsets.zero, child: wrap( ListView( selectionController: controller, itemHeight: 20, length: 1, itemBuilder: buildDummy, ), ), ), ); controller.selectedIndex = 0; }); // Regression test for https://github.com/tvolkert/chicago/issues/6 testWidgets( 'updating itemBuilder invokes new builder when widget is rebuilt', (WidgetTester tester) async { ListItemBuilder builder(String text) { return ( BuildContext ctx, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { return Directionality( textDirection: TextDirection.ltr, child: Text(text), ); }; } await tester.pumpWidget( ScrollableListView( itemHeight: 20, length: 1, itemBuilder: builder('one'), ), ); expect(find.text('one'), findsOneWidget); await tester.pumpWidget( ScrollableListView( itemHeight: 20, length: 1, itemBuilder: builder('two'), ), ); expect(find.text('two'), findsOneWidget); }, ); testWidgets('Reassemble triggers itemBuilder', (WidgetTester tester) async { int buildCount = 0; Widget build( BuildContext c, int index, bool isSelected, bool isHighlighted, bool isDisabled, ) { buildCount++; return Directionality( textDirection: TextDirection.ltr, child: Text('text'), ); } await tester.pumpWidget( ScrollableListView(itemHeight: 20, length: 1, itemBuilder: build), ); expect(buildCount, 1); tester.binding.buildOwner!.reassemble(tester.binding.rootElement!); await tester.pump(); expect(buildCount, 2); }); group('ListViewSelectionController', () { test('selectedItems', () { final ListViewSelectionController controller = ListViewSelectionController(selectMode: SelectMode.multi); controller.selectedRanges = <Span>[Span(5, 2), Span.single(10)]; expect(controller.selectedItems, <int>[2, 3, 4, 5, 10]); }); test('setSelectedRanges only notifies if selection changes', () { final ListViewSelectionController controller = ListViewSelectionController(selectMode: SelectMode.multi); int notifications = 0; controller.addListener(() => notifications++); controller.selectedRanges = const <Span>[]; expect(notifications, 0); controller.selectedRanges = const <Span>[Span(0, 3), Span(5, 6)]; expect(notifications, 1); controller.selectedRanges = const <Span>[Span(0, 3), Span(5, 6)]; expect(notifications, 1); }); test('addSelectedRange only notifies if range not already selected', () { final ListViewSelectionController controller = ListViewSelectionController(selectMode: SelectMode.multi); int notifications = 0; controller.addListener(() => notifications++); controller.addSelectedRange(0, 3); expect(notifications, 1); controller.addSelectedRange(1, 2); expect(notifications, 1); }); test('removeSelectedRange only notifies if range already selected', () { final ListViewSelectionController controller = ListViewSelectionController(selectMode: SelectMode.multi); int notifications = 0; controller.addListener(() => notifications++); controller.removeSelectedRange(0, 3); expect(notifications, 0); }); test('clearSelection only notifies if range already selected', () { final ListViewSelectionController controller = ListViewSelectionController(selectMode: SelectMode.multi); int notifications = 0; controller.addListener(() => notifications++); controller.clearSelection(); expect(notifications, 0); }); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/radio_button_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('RadioButton smoke test', (WidgetTester tester) async { final controller = RadioButtonController<int>(1); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RadioButton<int>( value: 1, controller: controller, trailing: const Text('Test'), ), ), ); expect(find.byType(RadioButton<int>), findsOneWidget); expect(find.text('Test'), findsOneWidget); }); testWidgets('Can select a radio button', (WidgetTester tester) async { final controller = RadioButtonController<int>(1); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RadioButton<int>(value: 2, controller: controller), ), ); expect(controller.value, 1); await tester.tap(find.byType(RadioButton<int>)); await tester.pump(); expect(controller.value, 2); }); testWidgets('Selecting one deselects another', (WidgetTester tester) async { final controller = RadioButtonController<String>('A'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Column( children: <Widget>[ RadioButton<String>( value: 'A', controller: controller, trailing: const Text('A'), ), RadioButton<String>( value: 'B', controller: controller, trailing: const Text('B'), ), ], ), ), ); expect(controller.value, 'A'); await tester.tap(find.text('B'), warnIfMissed: false); await tester.pump(); expect(controller.value, 'B'); }); testWidgets('onSelected callback is invoked', (WidgetTester tester) async { final controller = RadioButtonController<int>(1); bool wasSelected = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RadioButton<int>( value: 2, controller: controller, onSelected: () => wasSelected = true, ), ), ); await tester.tap(find.byType(RadioButton<int>)); await tester.pump(); expect(wasSelected, isTrue); }); testWidgets('RadioButton is disabled', (WidgetTester tester) async { final controller = RadioButtonController<int>(1); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RadioButton<int>( value: 2, controller: controller, isEnabled: false, ), ), ); expect(controller.value, 1); await tester.tap(find.byType(RadioButton<int>)); await tester.pump(); // Value should not change because the button is disabled expect(controller.value, 1); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/rollup_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart' hide ListView, TableCell, TableRow; import 'package:flutter_test/flutter_test.dart'; void main() { // Regression test for https://github.com/tvolkert/chicago/issues/17 testWidgets('Expanded Rollup can paint multiple times', ( WidgetTester tester, ) async { final RollupController controller = RollupController(isExpanded: true); int frame = 0; Widget buildExpandedRollup() { frame++; return Directionality( textDirection: TextDirection.ltr, child: Rollup( controller: controller, heading: SizedBox(), childBuilder: (BuildContext context) { return SizedBox(width: frame.toDouble(), height: frame.toDouble()); }, ), ); } await tester.pumpWidget(buildExpandedRollup()); await tester.pumpWidget(buildExpandedRollup()); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/table_pane.test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart' hide TableCell, TableRow; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets( 'Relative-width column with colspan will be allocated enough to fit intrinsic width', (WidgetTester tester) async { await tester.pumpWidget( Row( textDirection: TextDirection.ltr, children: [ TablePane( columns: const <TablePaneColumn>[ TablePaneColumn(width: RelativeTablePaneColumnWidth()), TablePaneColumn(width: RelativeTablePaneColumnWidth()), ], children: [ TableRow( children: [ const TableCell( columnSpan: 2, child: SizedBox(width: 100, height: 10), ), EmptyTableCell(), ], ), ], ), ], ), ); RenderTablePane renderObject = tester.renderObject<RenderTablePane>( find.byType(TablePane), ); expect(renderObject.size.width, 100); expect(renderObject.metrics.columnWidths, [50, 50]); }, ); testWidgets( 'Relative-width column with colspan that exceeds width constraint will be sized down', (WidgetTester tester) async { await tester.pumpWidget( TablePane( columns: const <TablePaneColumn>[ TablePaneColumn(width: RelativeTablePaneColumnWidth()), TablePaneColumn(width: RelativeTablePaneColumnWidth()), ], children: [ TableRow( children: [ const TableCell( columnSpan: 2, child: SizedBox(width: 1000, height: 10), ), EmptyTableCell(), ], ), ], ), ); RenderTablePane renderObject = tester.renderObject<RenderTablePane>( find.byType(TablePane), ); expect(renderObject.size.width, 800); expect(renderObject.metrics.columnWidths, [400, 400]); }, ); testWidgets('todo', (WidgetTester tester) async { await tester.pumpWidget( Center( child: ConstrainedBox( constraints: BoxConstraints(minWidth: 400), child: TablePane( columns: const <TablePaneColumn>[ TablePaneColumn(width: RelativeTablePaneColumnWidth()), TablePaneColumn(width: RelativeTablePaneColumnWidth()), ], children: [ TableRow( children: [ const TableCell( columnSpan: 2, child: SizedBox(width: 100, height: 10), ), EmptyTableCell(), ], ), ], ), ), ), ); RenderTablePane renderObject = tester.renderObject<RenderTablePane>( find.byType(TablePane), ); expect(renderObject.size.width, 400); expect(renderObject.metrics.columnWidths, [200, 200]); }); testWidgets('indexOf works for basic table structure', ( WidgetTester tester, ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TablePane( columns: const <TablePaneColumn>[ TablePaneColumn(width: FixedTablePaneColumnWidth(100)), TablePaneColumn(width: FixedTablePaneColumnWidth(100)), ], children: [ TableRow(children: const [Text('0,0'), Text('0,1')]), TableRow(children: const [Text('1,0'), Text('1,1')]), ], ), ), ); expect( TablePane.offsetOf(tester.element(find.text('0,0'))), IndexedOffset(0, 0), ); expect( TablePane.offsetOf(tester.element(find.text('0,1'))), IndexedOffset(0, 1), ); expect( TablePane.offsetOf(tester.element(find.text('1,0'))), IndexedOffset(1, 0), ); expect( TablePane.offsetOf(tester.element(find.text('1,1'))), IndexedOffset(1, 1), ); expect( TablePane.offsetOf(tester.element(find.byType(Directionality))), isNull, ); }); testWidgets('indexOf works for complex table structure', ( WidgetTester tester, ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TablePane( columns: const <TablePaneColumn>[ TablePaneColumn(width: FixedTablePaneColumnWidth(100)), TablePaneColumn(width: FixedTablePaneColumnWidth(100)), ], children: [ MediaQuery( data: MediaQueryData(), child: TableRow( children: const [ SizedBox.square(dimension: 50, child: Text('0,0')), SizedBox.square(dimension: 50, child: Text('0,1')), ], ), ), MediaQuery( data: MediaQueryData(), child: TableRow( children: const [ SizedBox.square(dimension: 50, child: Text('1,0')), SizedBox.square(dimension: 50, child: Text('1,1')), ], ), ), ], ), ), ); expect( TablePane.offsetOf(tester.element(find.text('0,0'))), IndexedOffset(0, 0), ); expect( TablePane.offsetOf(tester.element(find.text('0,1'))), IndexedOffset(0, 1), ); expect( TablePane.offsetOf(tester.element(find.text('1,0'))), IndexedOffset(1, 0), ); expect( TablePane.offsetOf(tester.element(find.text('1,1'))), IndexedOffset(1, 1), ); expect( TablePane.offsetOf(tester.element(find.byType(Directionality))), isNull, ); }); testWidgets('TablePane.of works for basic table structure', ( WidgetTester tester, ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TablePane( columns: const <TablePaneColumn>[ TablePaneColumn(width: FixedTablePaneColumnWidth(100)), TablePaneColumn(width: FixedTablePaneColumnWidth(100)), ], children: [ TableRow(children: const [Text('0,0'), Text('0,1')]), TableRow(children: const [Text('1,0'), Text('1,1')]), ], ), ), ); expect( TablePane.of(tester.element(find.byType(TablePane))), same(tester.element(find.byType(TablePane))), ); expect( TablePane.of(tester.element(find.text('0,0'))), same(tester.element(find.byType(TablePane))), ); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/text_input_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { Widget wrap(Widget child) { return Localizations( locale: Locale('en', 'US'), delegates: [ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Builder( builder: (BuildContext context) { return MediaQuery( data: MediaQueryData.fromView(View.of(context)), child: Directionality( textDirection: TextDirection.ltr, child: Material( child: Navigator( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( settings: settings, builder: (BuildContext context) => child, ); }, ), ), ), ); }, ), ); } testWidgets('If autofocus is false, widget is not focused', ( WidgetTester tester, ) async { expect(tester.binding.focusManager.primaryFocus, isNull); await tester.pumpWidget(wrap(TextInput(autofocus: false))); BuildContext focusContext = tester.binding.focusManager.primaryFocus!.context!; expect(focusContext.findAncestorWidgetOfExactType<TextInput>(), isNull); }); testWidgets('If autofocus is true, widget is focused', ( WidgetTester tester, ) async { expect(tester.binding.focusManager.primaryFocus, isNull); await tester.pumpWidget(wrap(TextInput(autofocus: true))); BuildContext focusContext = tester.binding.focusManager.primaryFocus!.context!; expect(focusContext.findAncestorWidgetOfExactType<TextInput>(), isNotNull); }); testWidgets('Can render a TextInput with an onKeyEvent handler', ( WidgetTester tester, ) async { await tester.pumpWidget(wrap(TextInput(onKeyEvent: (KeyEvent event) {}))); expect(find.byType(TextInput), findsOneWidget); }); testWidgets('autofocus works with onKeyEvent handler', ( WidgetTester tester, ) async { expect(tester.binding.focusManager.primaryFocus, isNull); await tester.pumpWidget( wrap(TextInput(autofocus: true, onKeyEvent: (KeyEvent event) {})), ); BuildContext focusContext = tester.binding.focusManager.primaryFocus!.context!; expect(focusContext.findAncestorWidgetOfExactType<TextInput>(), isNotNull); }); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
test/widget_surveyor_test.dart
Dart
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:chicago/chicago.dart'; import 'package:flutter/widgets.dart' hide TableCell, TableRow; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('WidgetSurveyor returns correct unconstrained measurements', ( WidgetTester tester, ) async { const WidgetSurveyor surveyor = WidgetSurveyor(); final Size size = surveyor.measureWidget(SizedBox(width: 100, height: 200)); expect(size, const Size(100, 200)); }); testWidgets('WidgetSurveyor returns correct constrained measurements', ( WidgetTester tester, ) async { const WidgetSurveyor surveyor = WidgetSurveyor(); final Size size = surveyor.measureWidget( SizedBox(width: 100, height: 200), constraints: BoxConstraints(maxWidth: 80, maxHeight: 180), ); expect(size, const Size(80, 180)); }); testWidgets('WidgetSurveyor disposes of the widget tree', ( WidgetTester tester, ) async { const WidgetSurveyor surveyor = WidgetSurveyor(); final List<WidgetState> states = <WidgetState>[]; surveyor.measureWidget(SizedBox(child: TestStates(states: states))); expect(states, [WidgetState.initialized, WidgetState.disposed]); }); testWidgets('WidgetSurveyor does not pollute widget binding global keys', ( WidgetTester tester, ) async { final int initialCount = WidgetsBinding.instance.buildOwner!.globalKeyCount; const WidgetSurveyor surveyor = WidgetSurveyor(); surveyor.measureWidget( TestGlobalKeyPollution( key: GlobalKey(), expectedGlobalKeyCountInBinding: initialCount, expectedGlobalKeyCountInContextDuringInit: 2, expectedGlobalKeyCountInContextDuringDispose: 1, ), ); expect(WidgetsBinding.instance.buildOwner!.globalKeyCount, initialCount); }); } enum WidgetState { initialized, disposed } class TestStates extends StatefulWidget { const TestStates({required this.states}); final List<WidgetState> states; @override TestStatesState createState() => TestStatesState(); } class TestStatesState extends State<TestStates> { @override void initState() { super.initState(); widget.states.add(WidgetState.initialized); } @override void dispose() { widget.states.add(WidgetState.disposed); super.dispose(); } @override Widget build(BuildContext context) => Container(); } class TestGlobalKeyPollution extends StatefulWidget { const TestGlobalKeyPollution({ Key? key, required this.expectedGlobalKeyCountInBinding, required this.expectedGlobalKeyCountInContextDuringInit, required this.expectedGlobalKeyCountInContextDuringDispose, }) : super(key: key); final int expectedGlobalKeyCountInBinding; final int expectedGlobalKeyCountInContextDuringInit; final int expectedGlobalKeyCountInContextDuringDispose; @override TestGlobalKeyPollutionState createState() => TestGlobalKeyPollutionState(); } class TestGlobalKeyPollutionState extends State<TestGlobalKeyPollution> { @override void initState() { super.initState(); expect( WidgetsBinding.instance.buildOwner!.globalKeyCount, widget.expectedGlobalKeyCountInBinding, ); expect( context.owner!.globalKeyCount, widget.expectedGlobalKeyCountInContextDuringInit, ); } @override void dispose() { expect( WidgetsBinding.instance.buildOwner!.globalKeyCount, widget.expectedGlobalKeyCountInBinding, ); expect( context.owner!.globalKeyCount, widget.expectedGlobalKeyCountInContextDuringDispose, ); super.dispose(); } @override Widget build(BuildContext context) => Container(); }
zanderso/chicago
468
The Chicago widget set for Flutter
Dart
zanderso
Zachary Anderson
Google
bin/dash_commit_counts.dart
Dart
// Copyright 2025 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io' as io; import 'package:args/args.dart'; import 'package:github/github.dart' as g; // Add your github token here. const String githubApiKey = 'ADD YOUR API KEY HERE'; const List<String> flutterRepos = <String>[ 'flutter/flutter', 'flutter/packages', 'flutter/cocoon', 'flutter/flutter-intellij', 'flutter/devtools', 'flutter/tests', 'flutter/website', // Excluding these due to massive import and deletion PRs. //'flutter/samples', //'flutter/demos', //'flutter/codelabs', //'flutter/ai', ]; const List<String> dartRepos = <String>[ 'dart-lang/ai', 'dart-lang/sdk', 'dart-lang/web', 'dart-lang/source_gen', 'dart-lang/labs', 'dart-lang/i18n', 'dart-lang/pub', 'dart-lang/setup-dart', 'dart-lang/webdev', 'dart-lang/site-www', 'dart-lang/native', 'dart-lang/pub-dev', 'dart-lang/build', 'dart-lang/dartbug.com', 'dart-lang/dart-pad', 'dart-lang/homebrew-dart', 'dart-lang/mockito', 'dart-lang/core', 'dart-lang/tools', 'dart-lang/sample-pop_pop_win', 'dart-lang/dart_style', 'dart-lang/pana', 'dart-lang/test', 'dart-lang/dartdoc', 'dart-lang/ecosystem', 'dart-lang/flute', 'dart-lang/dart_ci', 'dart-lang/dart-docker', 'dart-lang/repo_manager', 'dart-lang/site-shared', 'dart-lang/chocolatey-packages', 'dart-lang/leak_tracker', 'dart-lang/http', 'dart-lang/shelf', 'dart-lang/grpc_cronet', 'dart-lang/dart-syntax-highlight', 'dart-lang/dart-lang.github.io', ]; const List<String> bots = <String>[ 'skia-flutter-autoroll', 'engine-flutter-autoroll', 'fluttergithubbot', 'dependabot[bot]', 'flutter-pub-roller-bot', 'auto-submit[bot]', 'github-actions[bot]', 'flutteractionsbot', 'DartDevtoolWorkflowBot', ]; ArgParser buildParser() { return ArgParser() ..addFlag( 'help', abbr: 'h', negatable: false, help: 'Print this usage information.', ) ..addFlag( 'verbose', abbr: 'v', negatable: false, help: 'Show additional command output.', ) ..addFlag('dart', negatable: false, help: 'Analyze the dart-lang repos', defaultsTo: false) ..addOption('members', help: 'Members list file. One github user id per line.') ..addOption('output', help: 'Where to write summary CSV data', mandatory: true) ..addOption('raw-output', help: 'Where to write raw pull request json data', mandatory: true); } void printUsage(ArgParser argParser) { print('Usage: dart repo_analysis.dart <flags> [arguments]'); print(argParser.usage); } void main(List<String> arguments) async { final ArgParser argParser = buildParser(); try { final ArgResults results = argParser.parse(arguments); bool verbose = false; // Process the parsed arguments. if (results.flag('help')) { printUsage(argParser); return; } if (results.flag('verbose')) { verbose = true; } if (verbose) { print('[VERBOSE] All arguments: ${results.arguments}'); } final Set<String> members; if (results.wasParsed('members')) { final io.File membersCsvFile = io.File(results.option('members') as String); members = findMembers(membersCsvFile); } else { members = <String>{}; } final io.File outputCsvFile = io.File(results.option('output') as String); final io.File rawOutputJson = io.File(results.option('raw-output') as String); final (Map<String, List<g.RepositoryCommit>>, Map<String, List<g.RepositoryCommit>>) countMaps; // Fetch data and write to the file. countMaps = await downloadCommitData( repos: results.flag('dart') ? dartRepos : flutterRepos, memberIDs: members, after: DateTime.utc(2025), ); processCommits(countMaps, outputCsvFile, rawOutputJson); } on FormatException catch (e) { // Print usage information if an invalid argument was provided. print(e.message); print(''); printUsage(argParser); } } void processCommits( (Map<String, List<g.RepositoryCommit>>, Map<String, List<g.RepositoryCommit>>) countMaps, io.File outputCsvFile, io.File rawOutputJson, ) { final Map<String, List<g.RepositoryCommit>> memberCommits = countMaps.$1; final Map<String, List<g.RepositoryCommit>> externalCommits = countMaps.$2; int memberCommitcount = 0; int memberAdditions = 0; int memberDeletions = 0; for (final String id in memberCommits.keys) { final List<g.RepositoryCommit> commits = memberCommits[id]!; memberCommitcount += commits.length; int additions = 0; int deletions = 0; for (final g.RepositoryCommit commit in commits) { if ((commit.stats?.additions ?? 0) > 100000 || (commit.stats?.deletions ?? 0) > 100000) { print('LARGE PR: ${commit.htmlUrl} from $id'); } additions += commit.stats?.additions ?? 0; deletions += commit.stats?.deletions ?? 0; } memberAdditions += additions; memberDeletions += deletions; outputCsvFile.writeAsStringSync( '$id,${commits.length},$additions,$deletions\n', mode: io.FileMode.append, flush: true, ); } outputCsvFile.writeAsStringSync(',,,\n', mode: io.FileMode.append, flush: true); int externalCommitcount = 0; int externalAdditions = 0; int externalDeletions = 0; for (final String id in externalCommits.keys) { final List<g.RepositoryCommit> commits = externalCommits[id]!; externalCommitcount += commits.length; int additions = 0; int deletions = 0; for (final g.RepositoryCommit commit in commits) { if ((commit.stats?.additions ?? 0) > 100000 || (commit.stats?.deletions ?? 0) > 100000) { print('LARGE PR: ${commit.htmlUrl} from $id'); } additions += commit.stats?.additions ?? 0; deletions += commit.stats?.deletions ?? 0; } externalAdditions += additions; externalDeletions += deletions; outputCsvFile.writeAsStringSync( '$id,${commits.length},$additions,$deletions\n', mode: io.FileMode.append, flush: true, ); } print('Members: ${memberCommits.length}'); print('nonMembers: ${externalCommits.length}'); print('Member PR count: $memberCommitcount'); print('nonMember PR count: $externalCommitcount'); print('Member additions: $memberAdditions'); print('nonMember additions: $externalAdditions'); print('Member deletions: $memberDeletions'); print('nonMember deletions: $externalDeletions'); final List<Map<String, dynamic>> json = []; for (final String id in memberCommits.keys) { final List<g.RepositoryCommit> commits = memberCommits[id]!; for (final g.RepositoryCommit commit in commits) { json.add(commit.toJson()); } } for (final String id in externalCommits.keys) { final List<g.RepositoryCommit> commits = externalCommits[id]!; for (final g.RepositoryCommit commit in commits) { json.add(commit.toJson()); } } rawOutputJson.writeAsStringSync(jsonEncode(json), flush: true); } Set<String> findMembers(io.File membersCsvFile) { final Set<String> members = <String>{}; final List<String> membersLines = membersCsvFile.readAsLinesSync(); members.addAll(membersLines); return members; } Future<T> callWithRetries<T>( // ignore: body_might_complete_normally Future<T> Function() f, { int retries = 5, }) async { int retryCount = 0; while (retryCount < retries) { try { return await f(); } catch (e) { retryCount += 1; if (retryCount >= retries) { rethrow; } await Future<void>.delayed(const Duration(seconds: 1)); } } throw Error(); } // Do not exceed 5000 requests in an hour. Future<void> pauseForRateLimit(g.GitHub github) async { final int? total = github.rateLimitLimit; final int? remaining = github.rateLimitRemaining; final DateTime? reset = github.rateLimitReset; // We won't be able to figure this out without this data, so // don't wait. Maybe the data will show up before the next // request. if (total == null || remaining == null || reset == null) { return; } final Duration timeUntilReset = reset.difference(DateTime.now()); // Don't exceed `remaining` requests within the `timeUntilReset` // duration. final int millis = timeUntilReset.inMilliseconds; // Evenly divide up the remain time among the remaining quota. final double delayInMillis = remaining == 0 ? millis.toDouble() : millis / remaining; print('Rate limit: Waiting ${delayInMillis.ceil()} ms. ' '($remaining/$total) reset in: $timeUntilReset'); return Future.delayed(Duration(milliseconds: delayInMillis.ceil())); } Future<g.RepositoryCommit?> getCommit( g.RepositoriesService service, String repo, String? sha ) async { if (sha == null) { return null; } try { return await callWithRetries(() async { final g.RepositorySlug slug = g.RepositorySlug.full(repo); await pauseForRateLimit(service.github); return service.getCommit(slug, sha); }, retries: 5); } catch (e) { print('Error: $e'); return null; } } Future<List<g.RepositoryCommit>> getCommits( g.RepositoriesService service, String repo, DateTime after, ) async { return callWithRetries(() async { final List<g.RepositoryCommit> commits = <g.RepositoryCommit>[]; final g.RepositorySlug slug = g.RepositorySlug.full(repo); await pauseForRateLimit(service.github); final StreamSubscription<g.RepositoryCommit> sub = service.listCommits( slug, since: after, ).listen( (g.RepositoryCommit commit) async { commits.add(commit); }, ); try { await sub.asFuture(); } catch (e) { try { await sub.cancel(); } catch (e) { // ignore. } rethrow; } return commits; }, retries: 5); } // The first element of the return tuple is the list of commits for each member. // The second element is the list of commits for each non-member. Future<(Map<String, List<g.RepositoryCommit>>, Map<String, List<g.RepositoryCommit>>)> downloadCommitData({ required List<String> repos, required Set<String> memberIDs, required DateTime after, }) async { final g.GitHub github = g.GitHub( auth: g.Authentication.withToken(githubApiKey), ); final g.RepositoriesService service = g.RepositoriesService(github); final Map<String, List<g.RepositoryCommit>> memberCommits = <String, List<g.RepositoryCommit>>{}; final Map<String, List<g.RepositoryCommit>> externalCommits = <String, List<g.RepositoryCommit>>{}; for (final String repo in repos) { io.stdout.write('Downloading commit data for "$repo"'); //await io.stdout.flush(); final List<g.RepositoryCommit> partialCommits; final List<g.RepositoryCommit> commits = []; try { partialCommits = await getCommits(service, repo, after); for (final g.RepositoryCommit commit in partialCommits) { final g.RepositoryCommit? fullCommit = await getCommit(service, repo, commit.sha); if (fullCommit == null) { continue; } commits.add(fullCommit); } } catch (e) { print('\nFailed to get commits for $repo: Error: $e'); print( '\nrateLimitLimit: ${github.rateLimitLimit} ' 'rateLimitRemaining: ${github.rateLimitRemaining} ' 'rateLimitReset: ${github.rateLimitReset!.toLocal()}', ); break; } for (final g.RepositoryCommit commit in commits) { if (commit.author == null || commit.author!.login == null) { continue; } final String id = commit.author!.login!; if (bots.contains(id)) { continue; } if (memberIDs.contains(id)) { memberCommits.update( id, (List<g.RepositoryCommit> l) => l..add(commit), ifAbsent: () => <g.RepositoryCommit>[commit], ); } else { externalCommits.update( id, (List<g.RepositoryCommit> l) => l..add(commit), ifAbsent: () => <g.RepositoryCommit>[commit], ); } } io.stdout.write(': Done.\n'); // Vague attempt to avoid rate limiting. await Future.delayed(const Duration(minutes: 1)); } return (memberCommits, externalCommits); }
zanderso/dash-commit-stats
0
Fetches data from GitHub and analyzes information about commits across projects.
Dart
zanderso
Zachary Anderson
Google
bin/drt.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:drt/script_runner.dart' as script_runner; Future<void> main(List<String> arguments) async { await script_runner.main(arguments); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
examples/rainbow.dart
Dart
#!/usr/bin/env drt // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:chalkdart/chalk.dart'; void main() { // Get the width and height of the terminal. var width = stdout.terminalColumns; var height = stdout.terminalLines; // Draw the rainbow. for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Calculate the color of the pixel. double hue = (x / width) * 360; // Print the pixel. stdout.write(chalk.onHsl(hue, 100, 50)(' ')); } stdout.writeln(); } }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
examples/terminal_image.dart
Dart
#!/usr/bin/env drt // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'dart:math'; import 'package:args/args.dart' as args; import 'package:chalkdart/chalk.dart' as chalk; import 'package:image/image.dart' as image; void main(List<String> arguments) { final args.ArgParser argParser = args.ArgParser() ..addOption('input', abbr: 'i', help: 'Input image'); final args.ArgResults argResults = argParser.parse(arguments); final Options? options = Options.fromArgResults(argResults); if (options == null) { io.stderr.writeln(argParser.usage); io.exitCode = 1; return; } drawImageInTerminal(options.img!); } image.Pixel getPixel(image.Image image, double u, double v) => image.getPixel((u * image.width).toInt(), (v * image.height).toInt()); void drawPixelPair(image.Image img, double u, double v1, double v2) { const String upperHalfBlock = '\u2580'; final image.Pixel c1 = getPixel(img, u, v1); final image.Pixel c2 = getPixel(img, u, v2); final chalk.Chalk chlk = chalk.chalk.rgb(c1.r, c1.g, c1.b).onRgb(c2.r, c2.g, c2.b); io.stdout.write(chlk(upperHalfBlock)); } void drawImageInTerminal(image.Image img) { final int termWidth = io.stdout.terminalColumns; final int termHeight = 2 * (io.stdout.terminalLines - 2); final double scale = min(termWidth / img.width, termHeight / img.height); final int termImgWidth = (img.width * scale).toInt(); final int termImgHeight = (img.height * scale).toInt(); const String upperHalfBlock = '\u2580'; for (int i = 0; i < termImgHeight - 1; i += 2) { final double v1 = i / termImgHeight; final double v2 = (i + 1) / termImgHeight; for (int j = 0; j < termImgWidth; j++) { final double u = j / termImgWidth; drawPixelPair(img, u, v1, v2); } io.stdout.writeln(); } } class Options { Options._(this.img); final image.Image? img; static Options? fromArgResults(args.ArgResults results) { if (!results.wasParsed('input')) { io.stderr.writeln('Please supply an image with the --input flag.'); return null; } final String imgPath = results['input']!; final io.File inputFile = io.File(imgPath); if (!inputFile.existsSync()) { io.stderr.writeln('--input image "$imgPath" does not exist.'); return null; } return Options._(image.decodeImage(inputFile.readAsBytesSync())); } }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
examples/triangulate_image.dart
Dart
#!/usr/bin/env drt // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This program creates a png file of a delaunay trianulation of a random set // of points with colors taken from an input image. // // Run './triangulate_image.dart --help' for details. import 'dart:async'; import 'dart:io'; import 'dart:math'; import 'dart:typed_data'; import 'package:args/args.dart'; import 'package:delaunay/delaunay.dart'; import 'package:image/image.dart' as image; const String description = 'delaunay_example.dart: An example program that creates a random delaunay ' 'trianulation png file with colors from an input image.'; Future<int> main(List<String> args) async { final ArgParser argParser = ArgParser() ..addFlag( 'help', abbr: 'h', help: 'Print help', negatable: false, ) ..addFlag( 'verbose', abbr: 'v', help: 'Verbose output', negatable: false, ) ..addOption( 'input', abbr: 'i', help: 'Input image from which to extract colors for triangles', ) ..addOption( 'output', abbr: 'o', help: 'Path to the output file', defaultsTo: 'delaunay.png', ) ..addOption( 'points', abbr: 'p', help: 'Number of points', defaultsTo: '1000', ) ..addOption( 'seed', abbr: 's', help: 'RNG seed', defaultsTo: '42', ); final ArgResults argResults = argParser.parse(args); final Options? options = Options.fromArgResults(argResults); if (options == null || options.help) { stderr.writeln(description); stderr.writeln(); stderr.writeln(argParser.usage); return options == null ? 1 : 0; } if (options.inputImage == null) { return 1; } final image.Image inputImage = options.inputImage!; final Random r = Random(options.seed); const double minX = 0.0; final double maxX = inputImage.width.toDouble(); const double minY = 0.0; final double maxY = inputImage.height.toDouble(); final image.Image img = image.Image( width: inputImage.width, height: inputImage.height, ); final int numPoints = options.points; final List<Point<double>> points = <Point<double>>[]; for (int i = 0; i < numPoints; i++) { points.add(Point<double>(r.nextDouble() * maxX, r.nextDouble() * maxY)); } points.add(const Point<double>(minX, minY)); points.add(Point<double>(minX, maxY)); points.add(Point<double>(maxX, minY)); points.add(Point<double>(maxX, maxY)); final Delaunay triangulator = Delaunay.from(points); final Stopwatch sw = Stopwatch()..start(); triangulator.initialize(); if (options.verbose) { print('Triangulator initialized in ${sw.elapsedMilliseconds}ms.'); } sw.reset(); sw.start(); triangulator.processAllPoints(); if (options.verbose) { print('Triangulated with ${triangulator.triangles.length ~/ 3} triangles ' 'in ${sw.elapsedMilliseconds}ms'); } sw.reset(); sw.start(); for (int i = 0; i < triangulator.triangles.length; i += 3) { final Point<double> a = triangulator.getPoint( triangulator.triangles[i], ); final Point<double> b = triangulator.getPoint( triangulator.triangles[i + 1], ); final Point<double> c = triangulator.getPoint( triangulator.triangles[i + 2], ); final image.Pixel color = inputImage.getPixel( (a.x.toInt() + b.x.toInt() + c.x.toInt()) ~/ 3, (a.y.toInt() + b.y.toInt() + c.y.toInt()) ~/ 3, ); drawTriangle( img, a.x.round(), a.y.round(), b.x.round(), b.y.round(), c.x.round(), c.y.round(), image.ColorRgb8(0, 0, 0), // black color, ); } if (options.verbose) { print('Image drawn in ${sw.elapsedMilliseconds}ms.'); } sw.reset(); sw.start(); final List<int> imageData = image.encodePng(img, level: 2); File(options.output).writeAsBytesSync(imageData); sw.stop(); if (options.verbose) { print('PNG document written in ${sw.elapsedMilliseconds}ms.'); } return 0; } class Options { Options._( this.output, this.points, this.seed, this.verbose, this.help, this.inputImage, ); static Options? fromArgResults(ArgResults results) { final bool verbose = results['verbose']!; final int? points = int.tryParse(results['points']!); if (points == null || points <= 0) { stderr.writeln('--points must be a strictly positive integer'); return null; } final int? seed = int.tryParse(results['seed']!); if (seed == null || seed <= 0) { stderr.writeln('--seed must be a strictly positive integer'); return null; } final bool help = results['help']!; if (!results.wasParsed('input') && !help) { stderr.writeln('Please supply an image with the --input flag.'); return null; } return Options._( results['output']!, points, seed, verbose, results['help']!, _imageFromArgResults(results, verbose), ); } static image.Image? _imageFromArgResults(ArgResults results, bool verbose) { if (!results.wasParsed('input')) { return null; } final String inputImagePath = results['input']!; image.Image inputImage; final File inputFile = File(inputImagePath); if (!inputFile.existsSync()) { stderr.writeln('--input image "$inputImagePath" does not exist.'); return null; } final Stopwatch sw = Stopwatch(); sw.start(); final Uint8List imageData = inputFile.readAsBytesSync(); if (verbose) { final int kb = imageData.length >> 10; print('Image data (${kb}KB) read in ${sw.elapsedMilliseconds}ms'); } sw.reset(); inputImage = image.decodeImage(imageData)!; sw.stop(); if (verbose) { final int w = inputImage.width; final int h = inputImage.height; print('Image data ${w}x$h decoded in ${sw.elapsedMilliseconds}ms'); } return inputImage; } final String output; final int points; final int seed; final bool verbose; final bool help; final image.Image? inputImage; } void drawTriangle( image.Image img, int ax, int ay, int bx, int by, int cx, int cy, image.Color lineColor, image.Color fillColor, ) { void fillBottomFlat(int x1, int y1, int x2, int y2, int x3, int y3) { final double slope1 = (x2 - x1).toDouble() / (y2 - y1).toDouble(); final double slope2 = (x3 - x1).toDouble() / (y3 - y1).toDouble(); double curx1 = x1.toDouble(); double curx2 = curx1; for (int sy = y1; sy <= y2; sy++) { final int cx1 = curx1.toInt(); final int cx2 = curx2.toInt(); image.drawLine(img, x1: cx1, y1: sy, x2: cx2, y2: sy, color: fillColor); curx1 += slope1; curx2 += slope2; } } void fillTopFlat(int x1, int y1, int x2, int y2, int x3, int y3) { final double slope1 = (x3 - x1).toDouble() / (y3 - y1).toDouble(); final double slope2 = (x3 - x2).toDouble() / (y3 - y2).toDouble(); double curx1 = x3.toDouble(); double curx2 = curx1; for (int sy = y3; sy > y1; sy--) { final int cx1 = curx1.toInt(); final int cx2 = curx2.toInt(); image.drawLine(img, x1: cx1, y1: sy, x2: cx2, y2: sy, color: fillColor); curx1 -= slope1; curx2 -= slope2; } } // Sort points in ascending order by y coordinate. if (ay > cy) { final int tmpx = ax, tmpy = ay; ax = cx; ay = cy; cx = tmpx; cy = tmpy; } if (ay > by) { final int tmpx = ax, tmpy = ay; ax = bx; ay = by; bx = tmpx; by = tmpy; } if (by > cy) { final int tmpx = bx, tmpy = by; bx = cx; by = cy; cx = tmpx; cy = tmpy; } if (by == cy) { fillBottomFlat(ax, ay, bx, by, cx, cy); } else if (ay == by) { fillTopFlat(ax, ay, bx, by, cx, cy); } else { final int dy = by; final int dx = ax + (((by - ay).toDouble() / (cy - ay).toDouble()) * (cx - ax).toDouble()) .toInt(); fillBottomFlat(ax, ay, bx, by, dx, dy); fillTopFlat(bx, by, dx, dy, cx, cy); } }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
lib/script_runner.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io show exitCode, stdout; import 'package:args/args.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; import 'src/dartsdk.dart'; import 'src/import_extractor.dart'; import 'src/package_config_generator.dart'; export 'src/dartsdk.dart'; export 'src/import_extractor.dart'; export 'src/package_config_generator.dart'; abstract class Logger { void printLog(String message); void printError(String message); } class LocalLogger implements Logger { const LocalLogger(); @override void printLog(String message) => io.stdout.writeln(message); @override void printError(String message) => io.stdout.writeln('ERROR: $message'); } class ScriptRunner { ScriptRunner({ required this.fs, required this.dartSdk, required this.logger, required this.platform, this.offline = false, this.analyze = false, }); final FileSystem fs; final DartSDK dartSdk; final Logger logger; final Platform platform; final bool offline; final bool analyze; int _result = 0; int get result => _result; Future<void> run(List<String> arguments) async { if (!checkArguments(arguments)) { _result = 1; return; } if (!checkDart()) { _result = 1; return; } final int? appJitResult = await tryAppJit(arguments); if (appJitResult != null) { _result = appJitResult; return; } final String script = arguments[0]; final String packageConfigPath = await getPackageConfig(script); if (analyze) { await dartSdk.runDart(<String>[ 'analyze', '--packages=$packageConfigPath', script, ]); } else { final String appJitSnapshotPath = fs.path.join( fs.path.dirname(script), '.${fs.path.basenameWithoutExtension(script)}.jit', ); _result = await dartSdk.runDart(<String>[ '--disable-dart-dev', '--snapshot-kind=app-jit', '--snapshot=$appJitSnapshotPath', '--packages=$packageConfigPath', script, if (arguments.length > 1) ...arguments.sublist(1), ]); } } bool checkArguments(List<String> arguments) { if (arguments.isEmpty) { logger.printError('Missing script'); return false; } if (!fs.file(arguments[0]).existsSync()) { logger.printError('Script file "${arguments[0]}" not found'); return false; } return true; } bool checkDart() { if (!dartSdk.valid) { logger.printError( 'A "dart" executable could not be found. Make sure that a Dart SDK ' 'newer than 3.0 is on your PATH.', ); return false; } final (bool, String?) dartVersion = dartSdk.verifyDartVersion(); if (!dartVersion.$1) { logger.printError(dartVersion.$2!); return false; } return true; } Future<int?> tryAppJit(List<String> arguments) async { final String script = arguments[0]; final File scriptFile = fs.file(script); final String appJitSnapshotPath = fs.path.join( fs.path.dirname(script), '.${fs.path.basenameWithoutExtension(script)}.jit', ); // If the snapshot file exists, and the script hasn't been modified since // the snapshot was created, then run from the snapshot. final File appJitSnapshotFile = fs.file(appJitSnapshotPath); if (appJitSnapshotFile.existsSync()) { final DateTime snapshotModified = appJitSnapshotFile.lastModifiedSync(); final DateTime scriptModified = scriptFile.lastModifiedSync(); if (snapshotModified.isAfter(scriptModified)) { return dartSdk.runDart(<String>[ appJitSnapshotFile.path, if (arguments.length > 1) ...arguments.sublist(1), ]); } } // If the snapshot is stale, then delete it. if (appJitSnapshotFile.existsSync()) { try { appJitSnapshotFile.deleteSync(); } catch (_) { // Ignore. } } return null; } Future<String> getPackageConfig(String script) async { final File scriptFile = fs.file(script); final String packageConfigPath = fs.path.join( fs.path.dirname(script), '.${fs.path.basenameWithoutExtension(script)}.package_config.json', ); final File packageConfigFile = fs.file(packageConfigPath); final DateTime scriptModified = scriptFile.lastModifiedSync(); if (!packageConfigFile.existsSync() || packageConfigFile.lastModifiedSync().isBefore(scriptModified)) { if (packageConfigFile.existsSync()) { packageConfigFile.deleteSync(); } final Set<String> packages = PackageImportExtractor(fs: fs).getPackages(script); await PackageConfigGenerator( fs: fs, dartSdk: dartSdk, platform: platform, offline: offline, ).ensurePackageConfig(packages, packageConfigPath); } return packageConfigPath; } } Future<void> main(List<String> arguments) async { final ArgParser argParser = ArgParser(allowTrailingOptions: false); argParser.addFlag( 'analyze', abbr: 'a', negatable: false, help: 'Run the analyzer on the script instead of running it.', ); argParser.addFlag( 'help', abbr: 'h', negatable: false, help: 'Print help for this command.', ); argParser.addFlag( 'offline', negatable: false, help: 'Pass --offline to pub', ); final ArgResults parsedArguments = argParser.parse(arguments); if (parsedArguments['help'] as bool? ?? false) { io.stdout.writeln('This program runs standalone Dart scripts.'); io.stdout.writeln( 'usage: drt [drt options] path/to/script.dart [script arguments]'); io.stdout.writeln(argParser.usage); io.exitCode = 1; return; } const FileSystem fs = LocalFileSystem(); final DartSDK dartSdk = DartSDK( fs: fs, processManager: const LocalProcessManager(), platform: const LocalPlatform(), ); final ScriptRunner scriptRunner = ScriptRunner( fs: fs, dartSdk: dartSdk, logger: const LocalLogger(), platform: const LocalPlatform(), offline: parsedArguments['offline'] as bool? ?? false, analyze: parsedArguments['analyze'] as bool? ?? false, ); await scriptRunner.run(parsedArguments.rest); io.exitCode = scriptRunner.result; }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
lib/src/dartsdk.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' show Process, ProcessResult, ProcessStartMode; import 'package:file/file.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; class DartSDK { DartSDK({ required this.fs, required this.processManager, required this.platform, }); final FileSystem fs; final ProcessManager processManager; final Platform platform; bool get valid => dartExe != null; Future<int> runDart(List<String> arguments) async { final Process process = await processManager.start( <String>[dartExe!, ...arguments], mode: ProcessStartMode.inheritStdio, ); return process.exitCode; } Future<ProcessResult> runPub( List<String> arguments, { String? workingDirectory, }) { return processManager.run( <String>[dartExe!, 'pub', ...arguments], workingDirectory: workingDirectory, ); } (bool, String?) verifyDartVersion() { final String version = platform.version; final List<String> versionNumberParts = version.split('.'); final int? majorVersion = int.tryParse(versionNumberParts[0]); if (majorVersion == null) { return (false, 'Parsing Dart version string "$version" failed'); } if (majorVersion < 3) { return (false, 'The Dart version must be greater than 3.0.0: "$version"'); } return (true, null); } late final String? dartExe = () { // First see if the processManager knows how to find 'dart'. if (processManager.canRun('dart')) { return 'dart'; } // Otherwise, compute from `Platform.executable`, though this will be wrong // if this program is compiled into a self-contained binary from // `dart compile exe`. final String exe = platform.executable; final String dartGuess = fs.path.join( fs.path.dirname(exe), 'dart${fs.path.extension(exe)}', ); return fs.file(dartGuess).existsSync() ? dartGuess : null; }(); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
lib/src/import_extractor.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/analysis/utilities.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:file/file.dart'; class ImportVisitor extends RecursiveAstVisitor<void> { ImportVisitor({required this.fs, required this.scriptPath}); final FileSystem fs; final String scriptPath; final Set<String> packageImports = <String>{}; final Set<String> fsImports = <String>{}; @override void visitImportDirective(ImportDirective node) { final String? import = node.uri.stringValue; if (import == null) { // TODO(zra): Do something more useful here. print('ImportDirective with null uri.stringValue: "$node"'); return; } final Uri? uri = Uri.tryParse(import); if (uri == null) { // TODO(zra): Do something more useful here. print('ImportDirective was not a URI: "$import"'); return; } //print('uri: $uri, scheme: ${uri.scheme}'); if (uri.scheme == 'package') { final int indexOfColon = import.indexOf(':'); final int indexOfSlash = import.indexOf('/'); packageImports.add(import.substring(indexOfColon + 1, indexOfSlash)); } else if (uri.scheme == '') { // The uri is absolute or relative to the current file's path. if (fs.path.isAbsolute(import)) { fsImports.add(import); } else { fsImports.add(fs.path.canonicalize(fs.path.join( fs.path.dirname(scriptPath), import, ))); } } } } class PackageImportExtractor { PackageImportExtractor({required this.fs}); final FileSystem fs; Set<String> getPackages(String scriptPath) { final Set<String> visitedFsImports = <String>{}; final Set<String> unvisitedFsImports = <String>{scriptPath}; final Set<String> packageImports = <String>{}; do { final String script = unvisitedFsImports.first; final (Set<String>, Set<String>) imports = _getPackages(script); packageImports.addAll(imports.$1); visitedFsImports.add(script); unvisitedFsImports.remove(script); unvisitedFsImports.addAll(imports.$2); unvisitedFsImports.removeWhere( (String i) => visitedFsImports.contains(i), ); } while (unvisitedFsImports.isNotEmpty); return packageImports; } (Set<String>, Set<String>) _getPackages(String scriptPath) { final File scriptFile = fs.file(scriptPath); final ParseStringResult parseResult = parseString( content: scriptFile.readAsStringSync(), featureSet: FeatureSet.latestLanguageVersion(), ); final ImportVisitor visitor = ImportVisitor( fs: fs, scriptPath: scriptPath, ); visitor.visitCompilationUnit(parseResult.unit); return (visitor.packageImports, visitor.fsImports); } }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
lib/src/package_config_generator.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' show ProcessResult; import 'package:file/file.dart'; import 'package:package_config/package_config.dart'; import 'package:platform/platform.dart'; import 'dartsdk.dart'; class PackageConfigGenerator { PackageConfigGenerator({ required this.dartSdk, required this.fs, required this.platform, this.offline = false, }); static const String drtPackagesPathVar = 'DRT_PACKAGES_PATH'; final DartSDK dartSdk; final FileSystem fs; final Platform platform; final bool offline; String buildPubspecString(Set<String> packages) { final StringBuffer pubspecBuilder = StringBuffer() ..writeln('name: script') ..writeln('publish_to: none') ..writeln('environment:') ..writeln(" sdk: '>=3.0.0-0 <4.0.0'") ..writeln('dependencies:'); for (final String import in packages) { pubspecBuilder.writeln(' $import: any'); } final Map<String, String> packagesMap = makePackagesMap(); if (packages.any(packagesMap.containsKey)) { pubspecBuilder.writeln(); pubspecBuilder.writeln('dependency_overrides:'); for (final String import in packages) { if (!packagesMap.containsKey(import)) { continue; } pubspecBuilder.writeln(' $import:'); pubspecBuilder.writeln(' path: ${packagesMap[import]}'); } } return pubspecBuilder.toString(); } Future<void> ensurePackageConfig( Set<String> packages, String packageConfigPath, ) async { final File packageConfigFile = fs.file(packageConfigPath); // If it exists, see if the dot packages file already has everything. if (packageConfigFile.existsSync()) { final String packageConfigContents = packageConfigFile.readAsStringSync(); final PackageConfig packageConfig = PackageConfig.parseString( packageConfigContents, packageConfigFile.parent.uri, ); if (packages.every((String package) => packageConfig[package] != null)) { return; } } // The file does not exist, or it doesn't have all packages. Run pub to // write it into packageConfigFile. final String pubspecString = buildPubspecString(packages); await generatePackageConfig(pubspecString, packageConfigFile); } Future<void> generatePackageConfig( String pubspecString, File packageConfigFile, ) async { final Directory tempDir = fs.currentDirectory.createTempSync( 'drt_', ); try { final File pubspecFile = fs.file(fs.path.join(tempDir.path, 'pubspec.yaml')); pubspecFile.writeAsStringSync(pubspecString); final ProcessResult pubGetResult = await dartSdk.runPub( <String>['get', if (offline) '--offline'], workingDirectory: tempDir.path, ); if (pubGetResult.exitCode != 0) { print('pub get failed'); return; } final File packageConfigJson = fs.file(fs.path.join( tempDir.path, '.dart_tool', 'package_config.json', )); packageConfigJson.copySync(packageConfigFile.path); } finally { try { tempDir.deleteSync(recursive: true); } catch (_) { // Ignore. } } } Map<String, String> makePackagesMap() { final String? drtPackagesPath = platform.environment[drtPackagesPathVar]; if (drtPackagesPath == null) { return <String, String>{}; } final List<String> searchPaths = drtPackagesPath.split(':'); final Map<String, String> packageMap = <String, String>{}; for (final String p in searchPaths) { final Directory dir = fs.directory(p); if (!dir.existsSync()) { continue; } for (final Directory subdir in dir.listSync().whereType<Directory>()) { final String packageName = fs.path.basename(subdir.path); if (!packageMap.containsKey(packageName)) { packageMap[packageName] = subdir.absolute.path; } } } return packageMap; } }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/dartsdk_test.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:drt/script_runner.dart'; import 'package:file/memory.dart'; import 'package:platform/platform.dart'; import 'src/fake_process_manager.dart'; import 'src/test_wrapper.dart'; void main() { group('DartSDK', () { late MemoryFileSystem fs; late FakeProcessManager fakeProcessManager; setUp(() { fs = MemoryFileSystem.test(); fakeProcessManager = FakeProcessManager.empty(); }); test('FakeProcessManager canRun "dart"', () { final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(), ); // FakeProcessManager returns true for `canRun` unless instructed // otherwise. expect(dartSdk.dartExe, isNotNull); }); test('dartExe is non-null when it can be found from the platform', () { final String exePath = fs.path.join('path', 'to', 'dartaotruntime'); final String dartPath = fs.path.join('path', 'to', 'dart'); fs.file(exePath).createSync(recursive: true); fs.file(dartPath).createSync(recursive: true); fakeProcessManager.excludedExecutables = <String>{'dart'}; final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(executable: exePath), ); // FakeProcessManager returns true for `canRun` unless instructed // otherwise. expect(dartSdk.dartExe, equals(dartPath)); }); test( 'dartExe is non-null when it can be found from the platform with an extension', () { final String exePath = fs.path.join('path', 'to', 'dartaotruntime.exe'); final String dartPath = fs.path.join('path', 'to', 'dart.exe'); fs.file(exePath).createSync(recursive: true); fs.file(dartPath).createSync(recursive: true); fakeProcessManager.excludedExecutables = <String>{'dart', 'dart.exe'}; final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(executable: exePath), ); // FakeProcessManager returns true for `canRun` unless instructed // otherwise. expect(dartSdk.dartExe, equals(dartPath)); }); test('verifyDartVersion succeeds when the version string is good', () { final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(version: '3.1.0-56.0.dev'), ); expect(dartSdk.verifyDartVersion(), equals((true, null))); }); test('verifyDartVersion fails when the version string is malformed', () { final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(version: 'a.1.0-56.0.dev'), ); final (bool, String?) result = dartSdk.verifyDartVersion(); expect(result.$1, isFalse); expect(result.$2, isNotNull); }); test('verifyDartVersion fails when the version string is too low', () { final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(version: '2.1.0-56.0.dev'), ); final (bool, String?) result = dartSdk.verifyDartVersion(); expect(result.$1, isFalse); expect(result.$2, isNotNull); }); test('runDart does something reasonable', () async { fakeProcessManager.addCommand(const FakeCommand( command: <String>['dart', 'run', 'some_script.dart'], )); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(), ); final int result = await dartSdk.runDart(<String>[ 'run', 'some_script.dart', ]); expect(result, equals(0)); }); test('runPub does something reasonable', () async { fakeProcessManager.addCommand(const FakeCommand( command: <String>['dart', 'pub', 'get'], )); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(), ); final io.ProcessResult result = await dartSdk.runPub(<String>['get']); expect(result.exitCode, equals(0)); }); test('runPub plumbs the working directory', () async { const String workingDirectory = 'working_directory'; fakeProcessManager.addCommand(const FakeCommand( command: <String>['dart', 'pub', 'get'], workingDirectory: workingDirectory, )); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: FakePlatform(), ); final io.ProcessResult result = await dartSdk.runPub( <String>['get'], workingDirectory: workingDirectory, ); expect(result.exitCode, equals(0)); }); }); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/import_extractor_test.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:drt/script_runner.dart'; import 'package:file/memory.dart'; import 'src/test_wrapper.dart'; void main() { group('PackageImportExtractor', () { late MemoryFileSystem fs; setUp(() { fs = MemoryFileSystem.test(); }); test('Extracts package imports from a script', () { const String scriptContents = ''' import 'dart:io' show exitCode, Process, ProcessResult, ProcessStartMode; import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/analysis/utilities.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:args/args.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:package_config/package_config.dart'; import 'package:path/path.dart' as path; import 'package:platform/platform.dart'; import 'package:process/process.dart'; void main() {} '''; final String scriptPath = fs.path.join('path', 'to', 'script.dart'); fs.file(scriptPath) ..createSync(recursive: true) ..writeAsStringSync(scriptContents); final PackageImportExtractor extractor = PackageImportExtractor( fs: fs, ); final Set<String> packages = extractor.getPackages(scriptPath); final List<String> sortedPackages = List<String>.of(packages)..sort(); expect( sortedPackages, equals(<String>[ 'analyzer', 'args', 'file', 'package_config', 'path', 'platform', 'process', ])); }); }); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/integration_test.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io' as io; import 'dart:isolate'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; import 'src/test_wrapper.dart'; Future<void> main() async { const FileSystem fs = LocalFileSystem(); const Platform platform = LocalPlatform(); const ProcessManager pm = LocalProcessManager(); final String dart = platform.executable; final String packageConfigPath = (await Isolate.packageConfig)!.toFilePath( windows: platform.isWindows, ); final Directory packageRoot = fs.file(packageConfigPath).parent.parent; final Directory libDirectory = packageRoot.childDirectory('lib'); final Directory binDirectory = packageRoot.childDirectory('bin'); final File binDrt = binDirectory.childFile('drt.dart'); final File libScriptRunner = libDirectory.childFile('script_runner.dart'); final File drtExe = platform.isWindows ? binDirectory.childFile('drt.exe') : binDirectory.childFile('drt'); final io.ProcessResult result = await pm.run(<String>[ dart, 'compile', 'exe', '-o', drtExe.path, binDrt.path, ]); if (result.exitCode != 0) { print( 'Failed to compile ${binDrt.path} to exe:\n${result.stdout}\n${result.stderr}'); io.exitCode = 1; return; } final Directory testDirectory = packageRoot.childDirectory('test'); final Directory scriptsDirectory = testDirectory.childDirectory('scripts'); // Cleanup. setUp(() { cleanupDirectory(scriptsDirectory); }); tearDown(() { cleanupDirectory(scriptsDirectory); }); tearDownAll(() { tryDelete(drtExe); }); test('Run a script', () async { final File echoScriptFile = scriptsDirectory.childFile( 'echo_arguments.dart', ); final io.ProcessResult echoResult = await pm.run(<String>[ drtExe.path, echoScriptFile.path, 'a', 'b', ]); // The script emits the correct results. expect(echoResult.exitCode, equals(0)); final String expected = '${fs.path.join('arg', 'a')}\n' '${fs.path.join('arg', 'b')}\n'; final String fixedStdout = (echoResult.stdout as String).replaceAll('\r\n', '\n'); expect(fixedStdout, equals(expected)); // The package config and app-jit snapshot are created. expect( scriptsDirectory.childFile('.echo_arguments.jit').existsSync(), isTrue, ); expect( scriptsDirectory .childFile( '.echo_arguments.package_config.json', ) .existsSync(), isTrue, ); }); test('Run a script twice', () async { final File echoScriptFile = scriptsDirectory.childFile( 'echo_arguments.dart', ); io.ProcessResult echoResult = await pm.run(<String>[ drtExe.path, echoScriptFile.path, 'a', 'b', ]); expect(echoResult.exitCode, equals(0)); final String expected = '${fs.path.join('arg', 'a')}\n' '${fs.path.join('arg', 'b')}\n'; final String fixedStdout = (echoResult.stdout as String).replaceAll('\r\n', '\n'); expect(fixedStdout, equals(expected)); // A second run produces the right results as well. echoResult = await pm.run(<String>[ drtExe.path, echoScriptFile.path, 'a', 'b', ]); // The script emits the correct results. expect(fixedStdout, equals(expected)); }); test('Stdin/out are plumbed correctly', () async { final File echoScriptFile = scriptsDirectory.childFile('echo_stdin.dart'); final io.Process process = await pm.start(<String>[ drtExe.path, echoScriptFile.path, ]); process.stdin.writeln('hello'); process.stdin.writeln('world'); process.stdin.writeln('quit'); final StringBuffer stdoutBuffer = StringBuffer(); late List<String> stdoutLines; process.stdout.listen((List<int> data) { stdoutBuffer.write(utf8.decode(data)); }, onDone: () { stdoutLines = const LineSplitter().convert(stdoutBuffer.toString()); }); final StringBuffer stderrBuffer = StringBuffer(); late String stderrString; process.stderr.listen((List<int> data) { stderrBuffer.write(utf8.decode(data)); }, onDone: () { stderrString = stderrBuffer.toString(); }); final int processResult = await process.exitCode; if (processResult != 0) { print('stderr: $stderrString'); } expect(stdoutLines, equals(<String>['hello', 'world', 'quit'])); expect(processResult, equals(0)); }); test('File with a shebang can be run', () async { final File shebangScriptFile = scriptsDirectory.childFile( 'shebang.dart', ); final String? pathEnvVar = platform.environment['PATH']; expect(pathEnvVar, isNotNull); final String newPathEnvVar = '$pathEnvVar:${binDirectory.path}'; final io.ProcessResult result = await pm.run( <String>[shebangScriptFile.path], environment: <String, String>{'PATH': newPathEnvVar}, ); if (result.exitCode != 0) { print(result.stderr); print(result.stdout); } expect(result.exitCode, equals(0)); expect(result.stdout, equals('Hello, world!\n')); }, skip: platform.isWindows); test('The script runner can run itself', () async { final File echoScriptFile = scriptsDirectory.childFile( 'echo_arguments.dart', ); final io.ProcessResult result = await pm.run(<String>[ drtExe.path, libScriptRunner.path, echoScriptFile.path, 'a', 'b', ]); cleanupDirectory(binDirectory); cleanupDirectory(libDirectory); if (result.exitCode != 0) { print(result.stderr); print(result.stdout); } expect(result.exitCode, equals(0)); final String expected = '${fs.path.join('arg', 'a')}\n' '${fs.path.join('arg', 'b')}\n'; final String fixedStdout = (result.stdout as String).replaceAll('\r\n', '\n'); expect(fixedStdout, equals(expected)); }, timeout: const Timeout(Duration(minutes: 2))); } void tryDelete(FileSystemEntity fse) { try { fse.deleteSync(); } catch (e) { // Ignore. } } void cleanupDirectory(Directory dir) { for (final File f in dir.listSync().whereType<File>()) { if (f.path.endsWith('.jit') || f.path.endsWith('.json')) { tryDelete(f); } } }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/package_config_generator_test.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:drt/script_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:platform/platform.dart'; import 'src/fake_process_manager.dart'; import 'src/test_wrapper.dart'; void main() { group('PackageConfigGenerator', () { late MemoryFileSystem fs; late FakeProcessManager fakeProcessManager; late Platform platform; setUp(() { fs = MemoryFileSystem.test(); fakeProcessManager = FakeProcessManager.empty(); platform = FakePlatform(environment: <String, String>{}); }); test('can build pubspec.yaml string', () { final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final PackageConfigGenerator generator = PackageConfigGenerator( dartSdk: dartSdk, fs: fs, platform: platform, ); final String pubspec = generator.buildPubspecString(<String>{'analyzer'}); expect(pubspec, contains('dependencies:\n analyzer: any')); }); test('can generate package config from pubspec', () async { const String tempDirPath = '/drt_rand0'; const String packageConfigContents = 'package config contents'; fakeProcessManager.addCommand(FakeCommand( command: const <String>['dart', 'pub', 'get'], workingDirectory: tempDirPath, onRun: () { final String packageConfigPath = fs.path.join( tempDirPath, '.dart_tool', 'package_config.json', ); fs.file(packageConfigPath) ..createSync(recursive: true) ..writeAsStringSync(packageConfigContents); }, )); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final PackageConfigGenerator generator = PackageConfigGenerator( dartSdk: dartSdk, fs: fs, platform: platform, ); final String pubspec = generator.buildPubspecString(<String>{'analyzer'}); final File packageConfigFile = fs.file('package_config_file'); await generator.generatePackageConfig(pubspec, packageConfigFile); expect( packageConfigFile.readAsStringSync(), equals(packageConfigContents), ); }); test('uses existing package config file when possible', () async { const String packageConfigContents = ''' { "configVersion": 2, "packages": [ { "name": "args", "rootUri": "file:///Users/zra/.pub-cache/hosted/pub.dev/args-2.4.1", "packageUri": "lib/", "languageVersion": "2.18" }, { "name": "path", "rootUri": "file:///Users/zra/.pub-cache/hosted/pub.dev/path-1.8.3", "packageUri": "lib/", "languageVersion": "2.12" }, { "name": "script", "rootUri": "../", "packageUri": "lib/", "languageVersion": "3.0" } ], "generated": "2023-05-04T01:38:42.045701Z", "generator": "pub", "generatorVersion": "3.1.0-56.0.dev" }'''; final String packageConfigPath = fs.path.join( '/path', 'to', 'package_config.json', ); fs.file(packageConfigPath) ..createSync(recursive: true) ..writeAsStringSync(packageConfigContents); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final PackageConfigGenerator generator = PackageConfigGenerator( dartSdk: dartSdk, fs: fs, platform: platform, ); // This will try to call 'pub' and fail if the fast path check fails // because 'dart pub get' won't be in the fakePackageManager. await generator.ensurePackageConfig( <String>{'args', 'path', 'script'}, packageConfigPath, ); }); test( 'falls back on pub when an existing package config is missing something', () async { const String packageConfigContents = ''' { "configVersion": 2, "packages": [ { "name": "args", "rootUri": "file:///Users/zra/.pub-cache/hosted/pub.dev/args-2.4.1", "packageUri": "lib/", "languageVersion": "2.18" }, { "name": "path", "rootUri": "file:///Users/zra/.pub-cache/hosted/pub.dev/path-1.8.3", "packageUri": "lib/", "languageVersion": "2.12" }, { "name": "script", "rootUri": "../", "packageUri": "lib/", "languageVersion": "3.0" } ], "generated": "2023-05-04T01:38:42.045701Z", "generator": "pub", "generatorVersion": "3.1.0-56.0.dev" }'''; final String packageConfigPath = fs.path.join( '/path', 'to', 'package_config.json', ); final File packageConfigFile = fs.file(packageConfigPath) ..createSync(recursive: true) ..writeAsStringSync(packageConfigContents); const String tempDirPath = '/drt_rand0'; const String newPackageConfigContents = 'package config contents'; fakeProcessManager.addCommand(FakeCommand( command: const <String>['dart', 'pub', 'get'], workingDirectory: tempDirPath, onRun: () { final String packageConfigPath = fs.path.join( tempDirPath, '.dart_tool', 'package_config.json', ); fs.file(packageConfigPath) ..createSync(recursive: true) ..writeAsStringSync(newPackageConfigContents); }, )); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final PackageConfigGenerator generator = PackageConfigGenerator( dartSdk: dartSdk, fs: fs, platform: platform, ); // This will try to call 'pub' and fail if the fast path check fails // because 'dart pub get' won't be in the fakePackageManager. await generator.ensurePackageConfig( <String>{'analyzer', 'args', 'path', 'script'}, packageConfigPath, ); expect( packageConfigFile.readAsStringSync(), equals(newPackageConfigContents), ); }); }); group('PackageConfigGenerator with path overrides', () { late MemoryFileSystem fs; late FakeProcessManager fakeProcessManager; late Platform platform; late String packagesPath; setUp(() { fs = MemoryFileSystem.test(); packagesPath = fs.path.join('/path', 'to', 'packages'); fs.directory(packagesPath).createSync(recursive: true); fs.directory(packagesPath).childDirectory('args').createSync(); fs.directory(packagesPath).childDirectory('file').createSync(); fs.directory(packagesPath).childDirectory('path').createSync(); fakeProcessManager = FakeProcessManager.empty(); platform = FakePlatform(environment: <String, String>{ PackageConfigGenerator.drtPackagesPathVar: packagesPath, }); }); test('finds packages using the packages path', () { final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final PackageConfigGenerator generator = PackageConfigGenerator( dartSdk: dartSdk, fs: fs, platform: platform, ); final Map<String, String> packagesMap = generator.makePackagesMap(); expect( packagesMap, equals(<String, String>{ 'args': fs.path.join(packagesPath, 'args'), 'file': fs.path.join(packagesPath, 'file'), 'path': fs.path.join(packagesPath, 'path'), })); }); test('', () { final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final PackageConfigGenerator generator = PackageConfigGenerator( dartSdk: dartSdk, fs: fs, platform: platform, ); final String pubspec = generator.buildPubspecString(<String>{ 'args', 'file', }); expect(pubspec, contains('dependency_overrides:')); expect( pubspec, contains(' args:\n path: ${fs.path.join(packagesPath, "args")}'), ); expect( pubspec, contains(' file:\n path: ${fs.path.join(packagesPath, "file")}'), ); }); }); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/script_runner_test.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:drt/script_runner.dart'; import 'package:file/memory.dart'; import 'package:platform/platform.dart'; import 'src/fake_process_manager.dart'; import 'src/test_wrapper.dart'; class BufferLogger implements Logger { List<String> logs = <String>[]; List<String> errors = <String>[]; @override void printLog(String message) => logs.add(message); @override void printError(String message) => errors.add(message); } void main() { group('ScriptRunner', () { late MemoryFileSystem fs; late FakeProcessManager fakeProcessManager; setUp(() { fs = MemoryFileSystem.test(); fakeProcessManager = FakeProcessManager.empty(); }); test('runs normally without snapshot or package config', () async { const String script = '/script.dart'; const String scriptContents = ''' import 'package:process/process.dart'; void main() {} '''; const String appJitSnapshotPath = '/.script.jit'; const String packageConfigPath = '/.script.package_config.json'; const String tempDirPath = '/drt_rand0'; fakeProcessManager.addCommands(<FakeCommand>[ FakeCommand( command: const <String>['dart', 'pub', 'get'], workingDirectory: tempDirPath, onRun: () { final String packageConfigPath = fs.path.join( tempDirPath, '.dart_tool', 'package_config.json', ); fs.file(packageConfigPath).createSync(recursive: true); }, ), FakeCommand( command: const <String>[ 'dart', '--disable-dart-dev', '--snapshot-kind=app-jit', '--snapshot=$appJitSnapshotPath', '--packages=$packageConfigPath', script, ], onRun: () { fs.file(appJitSnapshotPath).createSync(recursive: true); }, ), ]); fs.file(script) ..createSync(recursive: true) ..writeAsStringSync(scriptContents); final Platform platform = FakePlatform( version: '3.1.0-56.0.dev', environment: <String, String>{}, ); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final ScriptRunner scriptRunner = ScriptRunner( fs: fs, dartSdk: dartSdk, logger: BufferLogger(), platform: platform, ); await scriptRunner.run(<String>[script]); expect(scriptRunner.result, equals(0)); expect(fs.file(appJitSnapshotPath).existsSync(), isTrue); }); test('runs normally with a snapshot', () async { const String script = '/script.dart'; const String appJitSnapshotPath = '/.script.jit'; fakeProcessManager.addCommands(<FakeCommand>[ const FakeCommand( command: <String>[ 'dart', appJitSnapshotPath, ], ), ]); fs.file(script).createSync(recursive: true); fs.file(appJitSnapshotPath).createSync(recursive: true); final Platform platform = FakePlatform(version: '3.1.0-56.0.dev'); final DartSDK dartSdk = DartSDK( fs: fs, processManager: fakeProcessManager, platform: platform, ); final ScriptRunner scriptRunner = ScriptRunner( fs: fs, dartSdk: dartSdk, logger: BufferLogger(), platform: platform, ); await scriptRunner.run(<String>[script]); expect(scriptRunner.result, equals(0)); }); }); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/scripts/echo_arguments.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:args/args.dart'; import 'package:path/path.dart' as path; void main(List<String> arguments) { final ArgParser argParser = ArgParser(); final ArgResults parsedArguments = argParser.parse(arguments); for (final String arg in parsedArguments.rest) { print(path.join('arg', arg)); } io.exitCode = 0; }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/scripts/echo_stdin.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; void main(List<String> arguments) { if (io.stdin.hasTerminal) { io.stdin.lineMode = false; io.stdin.echoMode = false; } while (true) { final String? input = io.stdin.readLineSync(); if (input == null) { break; } io.stdout.writeln(input); if (input == 'quit') { break; } } io.exitCode = 0; }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/scripts/shebang.dart
Dart
#!/usr/bin/env drt // Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. void main() { print('Hello, world!'); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/src/fake_process_manager.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io' as io show Process, ProcessResult, ProcessSignal, ProcessStartMode, systemEncoding; import 'package:file/file.dart'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'test_wrapper.dart'; export 'package:process/process.dart' show ProcessManager; typedef VoidCallback = void Function(); /// A command for [FakeProcessManager]. @immutable class FakeCommand { const FakeCommand({ required this.command, this.workingDirectory, this.environment, this.encoding, this.duration = Duration.zero, this.onRun, this.exitCode = 0, this.stdout = '', this.stderr = '', this.completer, this.stdin, this.exception, this.outputFollowsExit = false, }); /// The exact commands that must be matched for this [FakeCommand] to be /// considered correct. final List<Pattern> command; /// The exact working directory that must be matched for this [FakeCommand] to /// be considered correct. /// /// If this is null, the working directory is ignored. final String? workingDirectory; /// The environment that must be matched for this [FakeCommand] to be considered correct. /// /// If this is null, then the environment is ignored. /// /// Otherwise, each key in this environment must be present and must have a /// value that matches the one given here for the [FakeCommand] to match. final Map<String, String>? environment; /// The stdout and stderr encoding that must be matched for this [FakeCommand] /// to be considered correct. /// /// If this is null, then the encodings are ignored. final Encoding? encoding; /// The time to allow to elapse before returning the [exitCode], if this command /// is "executed". /// /// If you set this to a non-zero time, you should use a [FakeAsync] zone, /// otherwise the test will be artificially slow. final Duration duration; /// A callback that is run after [duration] expires but before the [exitCode] /// (and output) are passed back. final VoidCallback? onRun; /// The process' exit code. /// /// To simulate a never-ending process, set [duration] to a value greater than /// 15 minutes (the timeout for our tests). /// /// To simulate a crash, subtract the crash signal number from 256. For example, /// SIGPIPE (-13) is 243. final int exitCode; /// The output to simulate on stdout. This will be encoded as UTF-8 and /// returned in one go. final String stdout; /// The output to simulate on stderr. This will be encoded as UTF-8 and /// returned in one go. final String stderr; /// If provided, allows the command completion to be blocked until the future /// resolves. final Completer<void>? completer; /// An optional stdin sink that will be exposed through the resulting /// [FakeProcess]. final IOSink? stdin; /// If provided, this exception will be thrown when the fake command is run. final Object? exception; /// When true, stdout and stderr will only be emitted after the `exitCode` /// [Future] on [io.Process] completes. final bool outputFollowsExit; void _matches( List<String> command, String? workingDirectory, Map<String, String>? environment, Encoding? encoding, ) { final List<dynamic> matchers = this.command.map((Pattern x) => x is String ? x : matches(x)).toList(); expect(command, matchers); if (this.workingDirectory != null) { expect(workingDirectory, this.workingDirectory); } if (this.environment != null) { expect(environment, this.environment); } if (this.encoding != null) { expect(encoding, this.encoding); } } } /// A fake process for use with [FakeProcessManager]. /// /// The process delays exit until both [duration] (if specified) has elapsed /// and [completer] (if specified) has completed. /// /// When [outputFollowsExit] is specified, bytes are streamed to [stderr] and /// [stdout] after the process exits. @visibleForTesting class FakeProcess implements io.Process { FakeProcess({ int exitCode = 0, Duration duration = Duration.zero, this.pid = 1234, List<int> stderr = const <int>[], IOSink? stdin, List<int> stdout = const <int>[], Completer<void>? completer, bool outputFollowsExit = false, }) : _exitCode = exitCode, exitCode = Future<void>.delayed(duration).then((void value) { if (completer != null) { return completer.future.then((void _) => exitCode); } return exitCode; }), _stderr = stderr, stdin = stdin ?? IOSink(StreamController<List<int>>().sink), _stdout = stdout, _completer = completer { if (_stderr.isEmpty) { this.stderr = const Stream<List<int>>.empty(); } else if (outputFollowsExit) { // Wait for the process to exit before emitting stderr. this.stderr = Stream<List<int>>.fromFuture(this.exitCode.then((_) { // Return a Future so stderr isn't immediately available to those who // await exitCode, but is available asynchronously later. return Future<List<int>>(() => _stderr); })); } else { this.stderr = Stream<List<int>>.value(_stderr); } if (_stdout.isEmpty) { this.stdout = const Stream<List<int>>.empty(); } else if (outputFollowsExit) { // Wait for the process to exit before emitting stdout. this.stdout = Stream<List<int>>.fromFuture(this.exitCode.then((_) { // Return a Future so stdout isn't immediately available to those who // await exitCode, but is available asynchronously later. return Future<List<int>>(() => _stdout); })); } else { this.stdout = Stream<List<int>>.value(_stdout); } } /// The process exit code. final int _exitCode; /// When specified, blocks process exit until completed. final Completer<void>? _completer; @override final Future<int> exitCode; @override final int pid; /// The raw byte content of stderr. final List<int> _stderr; @override late final Stream<List<int>> stderr; @override final IOSink stdin; @override late final Stream<List<int>> stdout; /// The raw byte content of stdout. final List<int> _stdout; @override bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) { // Killing a fake process has no effect. return false; } } abstract class FakeProcessManager implements ProcessManager { /// A fake [ProcessManager] which responds to all commands as if they had run /// instantaneously with an exit code of 0 and no output. factory FakeProcessManager.any() = _FakeAnyProcessManager; /// A fake [ProcessManager] which responds to particular commands with /// particular results. /// /// On creation, pass in a list of [FakeCommand] objects. When the /// [ProcessManager] methods such as [start] are invoked, the next /// [FakeCommand] must match (otherwise the test fails); its settings are used /// to simulate the result of running that command. /// /// If no command is found, then one is implied which immediately returns exit /// code 0 with no output. /// /// There is no logic to ensure that all the listed commands are run. Use /// [FakeCommand.onRun] to set a flag, or specify a sentinel command as your /// last command and verify its execution is successful, to ensure that all /// the specified commands are actually called. factory FakeProcessManager.list(List<FakeCommand> commands) = _SequenceProcessManager; factory FakeProcessManager.empty() => _SequenceProcessManager(<FakeCommand>[]); FakeProcessManager._(); /// Adds a new [FakeCommand] to the current process manager. /// /// This can be used to configure test expectations after the [ProcessManager] has been /// provided to another interface. /// /// This is a no-op on [FakeProcessManager.any]. void addCommand(FakeCommand command); /// Add multiple [FakeCommand] to the current process manager. void addCommands(Iterable<FakeCommand> commands) { commands.forEach(addCommand); } final Map<int, FakeProcess> _fakeRunningProcesses = <int, FakeProcess>{}; /// Whether this fake has more [FakeCommand]s that are expected to run. /// /// This is always `true` for [FakeProcessManager.any]. bool get hasRemainingExpectations; /// The expected [FakeCommand]s that have not yet run. List<FakeCommand> get _remainingExpectations; @protected FakeCommand findCommand( List<String> command, String? workingDirectory, Map<String, String>? environment, Encoding? encoding, ); int _pid = 9999; FakeProcess _runCommand( List<String> command, String? workingDirectory, Map<String, String>? environment, Encoding? encoding, ) { _pid += 1; final FakeCommand fakeCommand = findCommand(command, workingDirectory, environment, encoding); if (fakeCommand.exception != null) { assert( fakeCommand.exception is Exception || fakeCommand.exception is Error); throw fakeCommand.exception!; // ignore: only_throw_errors } if (fakeCommand.onRun != null) { fakeCommand.onRun!(); } return FakeProcess( duration: fakeCommand.duration, exitCode: fakeCommand.exitCode, pid: _pid, stderr: encoding?.encode(fakeCommand.stderr) ?? fakeCommand.stderr.codeUnits, stdin: fakeCommand.stdin, stdout: encoding?.encode(fakeCommand.stdout) ?? fakeCommand.stdout.codeUnits, completer: fakeCommand.completer, outputFollowsExit: fakeCommand.outputFollowsExit, ); } @override Future<io.Process> start( List<dynamic> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, // ignored bool runInShell = false, // ignored io.ProcessStartMode mode = io.ProcessStartMode.normal, // ignored }) { final FakeProcess process = _runCommand(command.cast<String>(), workingDirectory, environment, io.systemEncoding); if (process._completer != null) { _fakeRunningProcesses[process.pid] = process; process.exitCode.whenComplete(() { _fakeRunningProcesses.remove(process.pid); }); } return Future<io.Process>.value(process); } @override Future<io.ProcessResult> run( List<dynamic> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, // ignored bool runInShell = false, // ignored Encoding? stdoutEncoding = io.systemEncoding, Encoding? stderrEncoding = io.systemEncoding, }) async { final FakeProcess process = _runCommand( command.cast<String>(), workingDirectory, environment, stdoutEncoding); await process.exitCode; return io.ProcessResult( process.pid, process._exitCode, stdoutEncoding == null ? process._stdout : await stdoutEncoding.decodeStream(process.stdout), stderrEncoding == null ? process._stderr : await stderrEncoding.decodeStream(process.stderr), ); } @override io.ProcessResult runSync( List<dynamic> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, // ignored bool runInShell = false, // ignored Encoding? stdoutEncoding = io.systemEncoding, Encoding? stderrEncoding = io.systemEncoding, }) { final FakeProcess process = _runCommand( command.cast<String>(), workingDirectory, environment, stdoutEncoding); return io.ProcessResult( process.pid, process._exitCode, stdoutEncoding == null ? process._stdout : stdoutEncoding.decode(process._stdout), stderrEncoding == null ? process._stderr : stderrEncoding.decode(process._stderr), ); } /// Returns false if executable in [excludedExecutables]. @override bool canRun(dynamic executable, {String? workingDirectory}) => !excludedExecutables.contains(executable); Set<String> excludedExecutables = <String>{}; @override bool killPid(int pid, [io.ProcessSignal signal = io.ProcessSignal.sigterm]) { // Killing a fake process has no effect unless it has an attached completer. final FakeProcess? fakeProcess = _fakeRunningProcesses[pid]; if (fakeProcess == null) { return false; } if (fakeProcess._completer != null) { fakeProcess._completer!.complete(); } return true; } } class _FakeAnyProcessManager extends FakeProcessManager { _FakeAnyProcessManager() : super._(); @override FakeCommand findCommand( List<String> command, String? workingDirectory, Map<String, String>? environment, Encoding? encoding, ) { return FakeCommand( command: command, workingDirectory: workingDirectory, environment: environment, encoding: encoding, ); } @override void addCommand(FakeCommand command) {} @override bool get hasRemainingExpectations => true; @override List<FakeCommand> get _remainingExpectations => <FakeCommand>[]; } class _SequenceProcessManager extends FakeProcessManager { _SequenceProcessManager(this._commands) : super._(); final List<FakeCommand> _commands; @override FakeCommand findCommand( List<String> command, String? workingDirectory, Map<String, String>? environment, Encoding? encoding, ) { expect(_commands, isNotEmpty, reason: 'ProcessManager was told to execute $command (in $workingDirectory) ' 'but the FakeProcessManager.list expected no more processes.'); _commands.first._matches(command, workingDirectory, environment, encoding); return _commands.removeAt(0); } @override void addCommand(FakeCommand command) { _commands.add(command); } @override bool get hasRemainingExpectations => _commands.isNotEmpty; @override List<FakeCommand> get _remainingExpectations => _commands; } /// Matcher that successfully matches against a [FakeProcessManager] with /// no remaining expectations ([item.hasRemainingExpectations] returns false). const Matcher hasNoRemainingExpectations = _HasNoRemainingExpectations(); class _HasNoRemainingExpectations extends Matcher { const _HasNoRemainingExpectations(); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) => item is FakeProcessManager && !item.hasRemainingExpectations; @override Description describe(Description description) => description.add('a fake process manager with no remaining expectations'); @override Description describeMismatch( dynamic item, Description description, Map<dynamic, dynamic> matchState, bool verbose, ) { final FakeProcessManager fakeProcessManager = item as FakeProcessManager; return description.add( 'has remaining expectations:\n${fakeProcessManager._remainingExpectations.map((FakeCommand command) => command.command).join('\n')}'); } }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
test/src/test_wrapper.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/test.dart' hide isInstanceOf; export 'package:test/test.dart' hide isInstanceOf; /// A matcher that compares the type of the actual value to the type argument T. TypeMatcher<T> isInstanceOf<T>() => isA<T>();
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
utils/install.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'dart:isolate'; import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; void cleanupDirectory(Directory dir) { for (final File f in dir.listSync().whereType<File>()) { if (f.path.endsWith('.jit') || f.path.endsWith('.json')) { f.deleteSync(); } } } String userHomePath(Platform platform) { final String envKey = platform.isWindows ? 'APPDATA' : 'HOME'; return platform.environment[envKey] ?? '.'; } void maybeAppendStringToFile( File file, String string, { required String guard, required String prompt, required String instruction, }) { if (!file.existsSync()) { return; } final String contents = file.readAsStringSync(); if (contents.contains(guard)) { return; } io.stdout.write(prompt); final String? response = io.stdin.readLineSync(); if (response == null || (response != 'Y' && response != 'y')) { return; } file.copySync('${file.path}.bak'); file.writeAsStringSync(string, mode: io.FileMode.append); io.stdout.writeln('Backup written to "${file.path}.bak"'); io.stdout.writeln(instruction); } void main() async { const FileSystem fs = LocalFileSystem(); const Platform platform = LocalPlatform(); const ProcessManager pm = LocalProcessManager(); final String dart = platform.executable; final String packageConfigPath = (await Isolate.packageConfig)!.path; final Directory packageRoot = fs.file(packageConfigPath).parent.parent; final Directory binDirectory = packageRoot.childDirectory('bin'); final Directory outDirectory = packageRoot.childDirectory('out'); final File binDrt = binDirectory.childFile('drt.dart'); final File drtExe = outDirectory.childFile('drt'); outDirectory.createSync(); final io.ProcessResult result = await pm.run(<String>[ dart, 'compile', 'exe', '-o', drtExe.path, binDrt.path, ]); if (result.exitCode != 0) { io.stderr.writeln('Build failure:\n${result.stdout}\n${result.stderr}'); io.exitCode = 1; return; } final Directory home = fs.directory(userHomePath(platform)); final File dotBashRc = home.childFile('.bashrc'); final File dotZshRc = home.childFile('.zshrc'); final StringBuffer buffer = StringBuffer(); buffer.writeln(); buffer.writeln('# >>> drt PATH setup'); buffer.writeln('export PATH="\$PATH:${outDirectory.path}"'); buffer.writeln('# <<< drt PATH setup'); maybeAppendStringToFile( dotBashRc, buffer.toString(), guard: 'drt PATH setup', prompt: 'Modify .bashrc to set PATH? (Y/N): ', instruction: 'Now, run: source ~/.bashrc', ); maybeAppendStringToFile( dotZshRc, buffer.toString(), guard: 'drt PATH setup', prompt: 'Modify .zshrc to set PATH? (Y/N): ', instruction: 'Now, run: source ~/.zshrc', ); }
zanderso/drt
7
A program that runs bare Dart scripts
Dart
zanderso
Zachary Anderson
Google
bin/bloaty.dart
Dart
import "dart:io"; class Symbol { String? name; String? type; int? shallowSize; int? retainedSize; List<Symbol> children = <Symbol>[]; Symbol compressTrivialPaths() { for (var i = 0; i < children.length; i++) { children[i] = children[i].compressTrivialPaths(); } if ((type == "path") && (children.length == 1) && (children[0].type == "path")) { return children[0]; } return this; } int computeRetainedSize() { var s = shallowSize!; for (var child in children) { s += child.computeRetainedSize(); } retainedSize = s; return s; } writeJson(StringBuffer out) { out.write("{"); out.write('"name": "$name",'); out.write('"shallowSize": $shallowSize,'); out.write('"retainedSize": $retainedSize,'); out.write('"type": "$type",'); out.write('"children": ['); bool first = true; for (var child in children) { if (first) { first = false; } else { out.write(","); } child.writeJson(out); } out.write("]}"); } } const filteredPathComponents = <String>[ "", ".", "..", "out", "xcodebuild", "src", "source", "third_party", "DebugX64", "ReleaseX64", "ProductX64", "DebugARM64", "ReleaseARM64", "ProductARM64", "DebugXARM64", "ReleaseXARM64", "ProductXARM64", ]; var cwd = Directory.current.path; String prettyPath(String path) { if (path.startsWith(cwd)) { path = path.substring(cwd.length); } return path .split("/") .where((component) => !filteredPathComponents.contains(component)) .join("/"); } main(List<String> args) { if (args.length != 3) { print("Usage: binary_size <stripped> <unstripped> <bloaty path>"); exit(1); } var strippedPath = args[0]; var unstrippedPath = args[1]; var bloatyPath = args[2]; var bloatyExec = bloatyPath; var bloatyArgs = [ "-d", "symbols,compileunits", "--domain=file", "-n", "0", "--csv", "--debug-file", unstrippedPath, strippedPath, ]; var bloatyResult = Process.runSync(bloatyExec, bloatyArgs); if (bloatyResult.exitCode != 0) { print("+ $bloatyExec ${bloatyArgs.join(' ')}"); print(bloatyResult.exitCode); print(bloatyResult.stdout); print(bloatyResult.stderr); exit(1); } var root = Symbol(); root.name = strippedPath; root.type = "path"; root.shallowSize = 0; var paths = <String, Symbol>{}; paths[""] = root; addToPath(Symbol s, String path) { Symbol? p = paths[path]; if (p == null) { p = Symbol(); p.name = path; p.type = "path"; p.shallowSize = 0; paths[path] = p; var i = path.lastIndexOf("/"); if (i != -1) { p.name = path.substring(i + 1); addToPath(p, path.substring(0, i)); } else { root.children.add(p); } } p.children.add(s); } var lines = bloatyResult.stdout.split("\n"); var header = true; for (var line in lines) { if (header) { header = false; continue; } if (line.isEmpty) { continue; } var columns = line.split(","); var name = columns[0]; var path = columns[1]; var vmSize = int.parse(columns[2]); var fileSize = int.parse(columns[3]); if (path.startsWith("[")) { if (path == name) { path = ""; } else if (name.contains("::")) { path = "(no path)/" + name.substring(0, name.lastIndexOf("::")).replaceAll("::", "/"); name = name.substring(name.lastIndexOf("::") + 2); } else { path = "(no path)"; } } path = prettyPath(path); var s = Symbol(); s.name = name; s.type = "symbol"; s.shallowSize = fileSize; addToPath(s, path); } root.compressTrivialPaths(); root.computeRetainedSize(); var json = StringBuffer(); root.writeJson(json); var html = viewer.replaceAll("__DATA__", json.toString()); File("$strippedPath.html").writeAsStringSync(html); // This written as a URL instead of path because some terminals will // automatically recognize it and make it a link. var url = Directory.current.uri.resolve("$strippedPath.html"); print("Wrote $url"); } var viewer = """ <html> <head> <style> .treemapTile { position: absolute; box-sizing: border-box; border: solid 1px; font-size: 13; text-align: center; overflow: hidden; white-space: nowrap; cursor: default; } </style> </head> <body> <script> var root = __DATA__; function hash(string) { // Jenkin's one_at_a_time. let h = string.length; for (let i = 0; i < string.length; i++) { h += string.charCodeAt(i); h += h << 10; h ^= h >> 6; } h += h << 3; h ^= h >> 11; h += h << 15; return h; } function color(string) { let hue = hash(string) % 360; return "hsl(" + hue + ",90%,80%)"; } function prettySize(size) { if (size < 1024) return size + "B"; size /= 1024; if (size < 1024) return size.toFixed(1) + "KiB"; size /= 1024; if (size < 1024) return size.toFixed(1) + "MiB"; size /= 1024; return size.toFixed(1) + "GiB"; } function createTreemapTile(v, width, height, depth) { let div = document.createElement("div"); div.className = "treemapTile"; div.style["background-color"] = color(v.type); div.ondblclick = function(event) { event.stopPropagation(); if (depth == 0) { let parent = v.parent; if (parent === undefined) { // Already at root. } else { showDominatorTree(parent); // Zoom out. } } else { showDominatorTree(v); // Zoom in. } }; let left = 0; let top = 0; const kPadding = 5; const kBorder = 1; left += kPadding - kBorder; top += kPadding - kBorder; width -= 2 * kPadding; height -= 2 * kPadding; div.title = v.name + " \\ntype: " + v.type + " \\nretained: " + v.retainedSize + " \\nshallow: " + v.shallowSize; if (width < 10 || height < 10) { // Too small: don't render label or children. return div; } let label = v.name + " [" + prettySize(v.retainedSize) + "]"; div.appendChild(document.createTextNode(label)); const kLabelHeight = 13; top += kLabelHeight; height -= kLabelHeight; if (depth > 2) { // Too deep: don't render children. return div; } if (width < 4 || height < 4) { // Too small: don't render children. return div; } let children = new Array(); v.children.forEach(function(c) { // Size 0 children seem to confuse the layout algorithm (accumulating // rounding errors?). if (c.retainedSize > 0) { children.push(c); } }); children.sort(function (a, b) { return b.retainedSize - a.retainedSize; }); const scale = width * height / v.retainedSize; // Bruls M., Huizing K., van Wijk J.J. (2000) Squarified Treemaps. In: de // Leeuw W.C., van Liere R. (eds) Data Visualization 2000. Eurographics. // Springer, Vienna. for (let rowStart = 0; // Index of first child in the next row. rowStart < children.length;) { // Prefer wider rectangles, the better to fit text labels. const GOLDEN_RATIO = 1.61803398875; let verticalSplit = (width / height) > GOLDEN_RATIO; let space; if (verticalSplit) { space = height; } else { space = width; } let rowMin = children[rowStart].retainedSize * scale; let rowMax = rowMin; let rowSum = 0; let lastRatio = 0; let rowEnd; // One after index of last child in the next row. for (rowEnd = rowStart; rowEnd < children.length; rowEnd++) { let size = children[rowEnd].retainedSize * scale; if (size < rowMin) rowMin = size; if (size > rowMax) rowMax = size; rowSum += size; let ratio = Math.max((space * space * rowMax) / (rowSum * rowSum), (rowSum * rowSum) / (space * space * rowMin)); if ((lastRatio != 0) && (ratio > lastRatio)) { // Adding the next child makes the aspect ratios worse: remove it and // add the row. rowSum -= size; break; } lastRatio = ratio; } let rowLeft = left; let rowTop = top; let rowSpace = rowSum / space; for (let i = rowStart; i < rowEnd; i++) { let child = children[i]; let size = child.retainedSize * scale; let childWidth; let childHeight; if (verticalSplit) { childWidth = rowSpace; childHeight = size / childWidth; } else { childHeight = rowSpace; childWidth = size / childHeight; } let childDiv = createTreemapTile(child, childWidth, childHeight, depth + 1); childDiv.style.left = rowLeft + "px"; childDiv.style.top = rowTop + "px"; // Oversize the final div by kBorder to make the borders overlap. childDiv.style.width = (childWidth + kBorder) + "px"; childDiv.style.height = (childHeight + kBorder) + "px"; div.appendChild(childDiv); if (verticalSplit) rowTop += childHeight; else rowLeft += childWidth; } if (verticalSplit) { left += rowSpace; width -= rowSpace; } else { top += rowSpace; height -= rowSpace; } rowStart = rowEnd; } return div; } function showDominatorTree(v) { // Add a filler div to the document first so the browser will calculate // the available width and height. let fill = document.createElement("div"); fill.style.width = "100%"; fill.style.height = "100%"; setBody(fill); let w = document.body.offsetWidth; let h = document.body.offsetHeight; let topTile = createTreemapTile(v, w, h, 0); topTile.style.width = w; topTile.style.height = h; setBody(topTile); // Encode the current view into the URL fragment. if (v == root) { window.location.hash = ""; } else { var fragment = v.name; v = v.parent; while (v != root) { fragment = v.name + "," + fragment; v = v.parent; } window.location.hash = fragment; } } function setBody(div) { let body = document.body; while (body.firstChild) { body.removeChild(body.firstChild); } body.appendChild(div); } function setParents(v) { v.children.forEach(function (child) { child.parent = v; setParents(child); }); } setParents(root); let v = root; let fragments = window.location.hash.substring(1).split(","); for (let i = 0; i < fragments.length; i++) { let fragment = fragments[i]; let foundChild = null; for (let j = 0; j < v.children.length; j++) { let child = v.children[j]; if (child.name == fragment) { foundChild = child; break; } } if (foundChild == null) break; // Not found, end search. v = foundChild; } showDominatorTree(v); </script> </body> </html> """;
zanderso/flutter_bloaty_action
1
Repo for testing github actions
Dart
zanderso
Zachary Anderson
Google
lib/main.dart
Dart
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is an example app showing how to load assets listed in the // 'shader' section of the 'flutter' manifest in the pubspec.yaml file. // A shader asset is loaded as a [FragmentProgram] object using the // `FragmentProgram.fromAsset()` method. Then, [Shader] objects can be obtained // from the `FragmentProgram.fragmentShader()` method, and uniforms set on // that object using `setFloat(index, value)`. // // The animation of a shader can be driven by passing the value of a Flutter // [Animation] as one of the float uniforms of the shader program. In this // example, the value of the animation is expected to be passed as the // float uniform at index 0. import 'dart:ui' as ui; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } /// A standard Material application container, like you'd get from Flutter's /// "Hello, world!" example. class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Shader Example', theme: ThemeData( brightness: Brightness.dark, primaryColor: Colors.blueGrey, ), home: const MyHomePage(title: 'Shader Example Home Page'), ); } } /// The body of the app. We'll use this stateful widget to manage initialization /// of the shader program. class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { bool _futuresInitialized = false; static const String _shaderKey = 'shaders/example.frag'; Future<void> _initializeFutures() async { // Loading the shader from an asset is an asynchronous operation, so we // need to wait for it to be loaded before we can use it to generate // Shader objects. await FragmentProgramManager.initialize(_shaderKey); if (!mounted) { return; } setState(() { _futuresInitialized = true; }); } @override void initState() { _initializeFutures(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ if (_futuresInitialized) AnimatedShader( program: FragmentProgramManager.lookup(_shaderKey), duration: const Duration(seconds: 10), size: const Size(300, 300), ) else const Text('Loading...'), ], ), ), ); } } /// A custom painter that updates the float uniform at index 0 with the /// current animation value and uses the shader to configure the Paint /// object that draws a rectangle onto the canvas. class AnimatedShaderPainter extends CustomPainter { AnimatedShaderPainter(this.shader, this.animation) : super(repaint: animation); final ui.FragmentShader shader; final Animation<double> animation; @override void paint(Canvas canvas, Size size) { shader.setFloat(0, animation.value); canvas.drawRect(Offset.zero & size, Paint()..shader = shader); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) => false; } /// This widget drives the animation of the AnimatedProgramPainter above. class AnimatedShader extends StatefulWidget { const AnimatedShader({ super.key, required this.program, required this.duration, required this.size, }); final ui.FragmentProgram program; final Duration duration; final Size size; @override State<AnimatedShader> createState() => AnimatedShaderState(); } class AnimatedShaderState extends State<AnimatedShader> with SingleTickerProviderStateMixin { late AnimationController _controller; late final ui.FragmentShader _shader; @override void initState() { super.initState(); _shader = widget.program.fragmentShader(); _shader.setFloat(0, 0.0); _shader.setFloat(1, widget.size.width.toDouble()); _shader.setFloat(2, widget.size.height.toDouble()); _controller = AnimationController( vsync: this, duration: widget.duration, lowerBound: 0.0, upperBound: 10.0, ) ..addListener(() { setState(() {}); }) ..addStatusListener((AnimationStatus status) { switch (status) { case AnimationStatus.completed: _controller.reverse(); break; case AnimationStatus.dismissed: _controller.forward(); break; default: break; } }) ..forward(); } @override void didUpdateWidget(AnimatedShader oldWidget) { super.didUpdateWidget(oldWidget); _controller.duration = widget.duration; } @override void dispose() { _controller.dispose(); _shader.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return CustomPaint( painter: AnimatedShaderPainter(_shader, _controller), size: widget.size, ); } } /// A utility class for initializing shader programs from asset keys. class FragmentProgramManager { static final Map<String, ui.FragmentProgram> _programs = <String, ui.FragmentProgram>{}; static Future<void> initialize(String assetKey) async { if (!_programs.containsKey(assetKey)) { final ui.FragmentProgram program = await ui.FragmentProgram.fromAsset( assetKey, ); _programs.putIfAbsent(assetKey, () => program); } } static ui.FragmentProgram lookup(String assetKey) => _programs[assetKey]!; }
zanderso/fragment_shader_example
26
A simple example of animating a custom shader in a Flutter app
Dart
zanderso
Zachary Anderson
Google
macos/Flutter/GeneratedPluginRegistrant.swift
Swift
// // Generated file. Do not edit. // import FlutterMacOS import Foundation func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { }
zanderso/fragment_shader_example
26
A simple example of animating a custom shader in a Flutter app
Dart
zanderso
Zachary Anderson
Google
macos/Runner/AppDelegate.swift
Swift
import Cocoa import FlutterMacOS @main class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { return true } }
zanderso/fragment_shader_example
26
A simple example of animating a custom shader in a Flutter app
Dart
zanderso
Zachary Anderson
Google
macos/Runner/MainFlutterWindow.swift
Swift
import Cocoa import FlutterMacOS class MainFlutterWindow: NSWindow { override func awakeFromNib() { let flutterViewController = FlutterViewController.init() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) super.awakeFromNib() } }
zanderso/fragment_shader_example
26
A simple example of animating a custom shader in a Flutter app
Dart
zanderso
Zachary Anderson
Google
test/widget_test.dart
Dart
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:fragment_shader_example/main.dart'; void main() { testWidgets('Smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); }); }
zanderso/fragment_shader_example
26
A simple example of animating a custom shader in a Flutter app
Dart
zanderso
Zachary Anderson
Google
bin/main.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // @dart=2.12 import 'package:args/args.dart'; import 'package:github/github.dart' as g; import 'package:github_commit_notifier/github_commit_watcher.dart'; import 'package:github_commit_notifier/notifier.dart'; import 'utils.dart'; int main(List<String> arguments) { final ArgResults? argResults = parseArguments(arguments); if (argResults == null) { return 1; } final List<String> repos = argResults['repos'] as List<String>; final g.GitHub github = g.GitHub( auth: g.findAuthenticationFromEnvironment(), client: NonPersistentClient(), ); final GitCommitWatcher watcher = GitCommitWatcher(github); final Notifier notifier = Notifier(); for (final String repo in repos) { final List<String> orgAndName = repo.split('/'); final String org = orgAndName[0]; final String name = orgAndName[1]; watcher.watch(org, name, (String title, String? url) async { return notifier.notify( appName: 'Flutter', title: '$org/$name Commit', body: title, image: 'bin/logo_flutter_square_large.png', url: url, onOpen: () async { if (url != null) { await openUrl(url); } }, onClose: () { print('Notification closed.'); }, ); }); } return 0; } ArgResults? parseArguments(List<String> arguments) { final ArgParser argParser = ArgParser() ..addMultiOption( 'repos', abbr: 'r', help: 'The repositories to watch, for example flutter/flutter,flutter/engine', ) ..addFlag( 'verbose', abbr: 'v', help: 'Verbose output', ); final ArgResults argResults = argParser.parse(arguments); if (!argResults.wasParsed('repos')) { print('Please specify some repositories'); return null; } return argResults; }
zanderso/github_commit_notifier
3
A command line program that generates desktop notifications on commits to specified GitHub repositories
Dart
zanderso
Zachary Anderson
Google
bin/utils.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:http/http.dart' as http; import 'package:http/io_client.dart' as http_io; /// Open the given URL in the user's default application for the URL's scheme. /// /// http and https URLs, for example, will be opened in the default browser. /// /// The default utility to open URLs for the platform is used. /// A process is spawned to run that utility, with the [ProcessResult] /// being returned. Future<io.ProcessResult> openUrl(String url) { return io.Process.run(_command, <String>[url], runInShell: true); } String get _command { if (io.Platform.isWindows) { return 'start'; } else if (io.Platform.isLinux) { return 'xdg-open'; } else if (io.Platform.isMacOS) { return 'open'; } else { throw UnsupportedError('Operating system not supported by the open_url ' 'package: ${io.Platform.operatingSystem}'); } } class NonPersistentClient extends http.BaseClient { NonPersistentClient() : client = http_io.IOClient( io.HttpClient()..idleTimeout = const Duration(seconds: 0), ); final http.Client client; @override Future<http.StreamedResponse> send(http.BaseRequest request) { request.persistentConnection = false; return client.send(request); } @override void close() { client.close(); } }
zanderso/github_commit_notifier
3
A command line program that generates desktop notifications on commits to specified GitHub repositories
Dart
zanderso
Zachary Anderson
Google
lib/github_commit_watcher.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:github/github.dart' as g; class GitCommitWatcher { GitCommitWatcher(this.github) : _activityService = g.ActivityService(github); final g.GitHub github; final g.ActivityService _activityService; final Map<String, g.EventPoller> _eventPollers = <String, g.EventPoller>{}; void watch( String org, String repo, Future<void> Function(String, String?) onCommit, ) { final g.EventPoller repoEventPoller = _activityService.pollRepositoryEvents( g.RepositorySlug(org, repo), ); _eventPollers['$org/$repo'] = repoEventPoller; final Stream<g.Event> repoEventStream = repoEventPoller.start( onlyNew: true, interval: 300, // secconds. ); repoEventStream.listen((g.Event event) async { final String? type = event.type; if (type == null) { return; } if (type != 'PullRequestEvent') { return; } final Map<String, dynamic>? payload = event.payload; if (payload == null) { return; } final String action = payload['action'] as String; if (action != 'closed') { return; } final Map<String, dynamic>? pullRequest = payload['pull_request'] as Map<String, dynamic>?; if (pullRequest == null) { return; } final String? title = pullRequest['title'] as String?; if (title == null) { return; } final String? mergedAt = pullRequest['merged_at'] as String?; if (mergedAt == null) { return; } final DateTime mergeTime = DateTime.parse(mergedAt); if (DateTime.now().difference(mergeTime) > const Duration(minutes: 5)) { return; } final String? htmlUrl = pullRequest['html_url'] as String?; print('New commit "$title" merged at $mergedAt: url: $htmlUrl'); try { await onCommit(title, htmlUrl); } on Exception catch (e) { print('onCommit failed: $e'); } }); } Future<void> unwatch(String org, String repo) async { final g.EventPoller? eventPoller = _eventPollers.remove('$org/$repo'); if (eventPoller == null) { return; } await eventPoller.stop(); } }
zanderso/github_commit_notifier
3
A command line program that generates desktop notifications on commits to specified GitHub repositories
Dart
zanderso
Zachary Anderson
Google
lib/notifier.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io show Platform; import 'src/linux_notifier.dart'; import 'src/mac_notifier.dart'; import 'src/windows_notifier.dart'; abstract class Notifier { factory Notifier() { if (io.Platform.isLinux) { return LinuxNotifier(); } else if (io.Platform.isMacOS) { return MacNotifier(); } else if (io.Platform.isWindows) { return WindowsNotifier(); } throw StateError( 'This program is not supported on ${io.Platform.operatingSystem}', ); } Future<void> notify({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }); }
zanderso/github_commit_notifier
3
A command line program that generates desktop notifications on commits to specified GitHub repositories
Dart
zanderso
Zachary Anderson
Google
lib/src/linux_notifier.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'package:desktop_notifications/desktop_notifications.dart' as d; import 'package:pedantic/pedantic.dart'; import '../notifier.dart'; class LinuxNotifier implements Notifier { LinuxNotifier(); @override Future<void> notify({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) async { final d.NotificationsClient notificationsClient = d.NotificationsClient(); try { final List<String> capabilities = await notificationsClient.getCapabilities(); for (final String c in capabilities) { print('Capability: $c'); } final io.File? icon = image != null ? io.File(image).absolute : null; final d.Notification notification = await notificationsClient.notify( title, appName: appName, body: body, hints: <d.NotificationHint>[ d.NotificationHint.actionIcons(), if (icon != null) d.NotificationHint.imagePath(icon.path), ], actions: const <d.NotificationAction>[ d.NotificationAction('document-open', 'Open PR'), ], ); final Completer<void> done = Completer<void>(); unawaited(notification.action.then((String action) async { if (onOpen != null) { final dynamic onOpenResult = onOpen(); if (onOpenResult is Future<dynamic>) { await onOpenResult; } } if (!done.isCompleted) { done.complete(); } })); unawaited(notification.closeReason .then((d.NotificationClosedReason reason) async { if (onClose != null) { final dynamic onCloseResult = onClose(); if (onCloseResult is Future<dynamic>) { await onCloseResult; } } if (!done.isCompleted) { done.complete(); } })); await done.future; } on Exception catch (e) { print('Failed to notify: $e'); } finally { await notificationsClient.close(); } } }
zanderso/github_commit_notifier
3
A command line program that generates desktop notifications on commits to specified GitHub repositories
Dart
zanderso
Zachary Anderson
Google
lib/src/mac_notifier.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import '../notifier.dart'; class MacNotifier implements Notifier { MacNotifier(); @override Future<void> notify({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) async { final bool terminalNotifierResult = await _terminalNotifierNotify( appName: appName, title: title, body: body, image: image, url: url, onOpen: onOpen, onClose: onClose, ); if (terminalNotifierResult) { return; } await _fallbackNotify( appName: appName, title: title, body: body, image: image, url: url, onOpen: onOpen, onClose: onClose, ); } Future<bool> _terminalNotifierNotify({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) async { try { final io.ProcessResult result = await io.Process.run( 'terminal-notifier', <String>[ '-title', '"$title"', '-subtitle', '"$appName"', '-message', '"$body"', if (image != null) ...<String>['-appIcon', '"$image"'], if (url != null) ...<String>['-open', '"$url"'], ], runInShell: true, ); if (result.exitCode != 0) { print('Result: ${result.exitCode}'); print('stdout:\n${result.stdout as String}'); print('stderr:\n${result.stderr as String}'); return false; } return true; } on Exception catch (e) { print('Error while running terminal-notifier: "$e"'); return false; } } Future<void> _fallbackNotify({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) async { final List<String> displayCommand = <String>[ 'display', 'notification', '"$body"', 'with', 'title', '"$title"', 'subtitle', '"$appName"', ]; final String display = displayCommand.join(' '); final io.ProcessResult result = await io.Process.run( 'osascript', <String>[ '-e', display, ], runInShell: true, ); if (result.exitCode != 0) { print('Result: ${result.exitCode}'); print('stdout:\n${result.stdout as String}'); print('stderr:\n${result.stderr as String}'); } } }
zanderso/github_commit_notifier
3
A command line program that generates desktop notifications on commits to specified GitHub repositories
Dart
zanderso
Zachary Anderson
Google
lib/src/windows_notifier.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:path/path.dart' as path; import '../notifier.dart'; class WindowsNotifier implements Notifier { WindowsNotifier(); @override Future<void> notify({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) async { final bool burntToastResult = await _burntToastNotifier( appName: appName, title: title, body: body, image: image, url: url, onOpen: onOpen, onClose: onClose, ); if (burntToastResult) { return; } await _fallbackNotifier( appName: appName, title: title, body: body, image: image, url: url, onOpen: onOpen, onClose: onClose, ); } Future<bool> _burntToastNotifier({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) { return _notify( _windowsPopupPS1, appName: appName, title: title, body: body, image: image, url: url, onOpen: onOpen, onClose: onClose, ); } Future<bool> _fallbackNotifier({ required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) { return _notify( _fallbackWindowsPopupPS1, appName: appName, title: title, body: body, image: image, url: url, onOpen: onOpen, onClose: onClose, ); } Future<bool> _notify( String scriptBody, { required String appName, required String title, required String body, String? image, String? url, dynamic Function()? onOpen, dynamic Function()? onClose, }) async { io.Directory? tempDir; try { tempDir = io.Directory.systemTemp.createTempSync( 'github', ); final io.File scriptFile = io.File(path.join(tempDir.path, 'script.ps1')) ..createSync(recursive: true) ..writeAsStringSync(scriptBody); final io.File? imageFile = image == null ? null : io.File(image).absolute; final String imageArg = imageFile == null ? '' : " -image '${imageFile.path}'"; final String urlArg = url == null ? '' : " -url '$url'"; final io.ProcessResult result = await io.Process.run( 'powershell.exe', <String>[ '-ExecutionPolicy', 'Bypass', '-Command', "${scriptFile.path} -appName '$appName' -headline '$title' -body '$body'$imageArg$urlArg", ], runInShell: true, ); if (result.exitCode != 0) { print('Result: ${result.exitCode}'); print('stdout:\n${result.stdout as String}'); print('stderr:\n${result.stderr as String}'); return false; } return true; } on Exception catch (e) { print('Error while running powershell script: $e'); return false; } finally { try { tempDir?.deleteSync(recursive: true); } on io.FileSystemException { // ignore. } } } } const String _windowsPopupPS1 = r''' param( [Parameter(Mandatory=$true)][string]$appName, [Parameter(Mandatory=$true)][string]$headline, [Parameter(Mandatory=$true)][string]$body, [string]$url, [string]$image ) #Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope CurrentUser #Install-Module -Name BurntToast -Scope CurrentUser $ToastHeader = New-BTHeader -Id '001' -Title "$headline" $Buttons = New-Object Collections.Generic.List[Object] if ($url -ne '') { $OpenButton = New-BTButton -Content 'Open PR' -Arguments "$url" $Buttons.add($OpenButton) } $CloseButton = New-BTButton -Dismiss $Buttons.add($CloseButton) if ($image -eq '') { New-BurntToastNotification -Text "$body" -Header $ToastHeader -Button $Buttons } else { New-BurntToastNotification -AppLogo "$image" -Text "$body" -Header $ToastHeader -Button $Buttons } '''; const String _fallbackWindowsPopupPS1 = r''' param( [Parameter(Mandatory=$true)][string]$appName, [Parameter(Mandatory=$true)][string]$headline, [Parameter(Mandatory=$true)][string]$body, [string]$url, [string]$image = $null ) [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] if ($image -eq '') { $Template = [Windows.UI.Notifications.ToastTemplateType]::ToastText02 #Gets the Template XML so we can manipulate the values [xml]$ToastTemplate = ([Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($Template).GetXml()) [xml]$ToastTemplate = @" <toast launch="app-defined-string"> <visual> <binding template="ToastText02"> <text id="1">$headline</text> <text id="2">$body</text> </binding> </visual> </toast> "@ } else { $Template = [Windows.UI.Notifications.ToastTemplateType]::ToastImageAndText02 #Gets the Template XML so we can manipulate the values [xml]$ToastTemplate = ([Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($Template).GetXml()) [xml]$ToastTemplate = @" <toast launch="app-defined-string"> <visual> <binding template="ToastImageAndText02"> <image id="1" src="$image" alt="image1"/> <text id="1">$headline</text> <text id="2">$body</text> </binding> </visual> </toast> "@ } $ToastXml = New-Object -TypeName Windows.Data.Xml.Dom.XmlDocument $ToastXml.LoadXml($ToastTemplate.OuterXml) $toast = [Windows.UI.Notifications.ToastNotification]::new($ToastXml) $notify = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appName) $notify.Show($toast) ''';
zanderso/github_commit_notifier
3
A command line program that generates desktop notifications on commits to specified GitHub repositories
Dart
zanderso
Zachary Anderson
Google
example/example.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:kmeans/kmeans.dart'; import '../test/utils/arff.dart'; Future<void> main() async { // See example/letter.arff for an explanation of the data. final ArffReader reader = ArffReader.fromFile(File('example/letter.arff')); await reader.parse(); const int labelIndex = 16; final int trainingSetSize = reader.data.length ~/ 2; // Train on the first half of the data. final List<List<double>> trainingData = reader.data.sublist(0, trainingSetSize); final KMeans trainingKMeans = KMeans(trainingData, labelDim: labelIndex); final Clusters trainingClusters = trainingKMeans.bestFit( minK: 26, maxK: 26, ); int trainingErrors = 0; for (int i = 0; i < trainingClusters.clusterPoints.length; i++) { // Count the occurrences of each label. final List<int> counts = List<int>.filled(trainingClusters.k, 0); for (int j = 0; j < trainingClusters.clusterPoints[i].length; j++) { counts[trainingClusters.clusterPoints[i][j][labelIndex].toInt()]++; } // Find the most frequent label. int maxIdx = -1; int maxCount = 0; for (int j = 0; j < trainingClusters.k; j++) { if (counts[j] > maxCount) { maxCount = counts[j]; maxIdx = j; } } // If a point isn't in the most frequent cluster, consider it an error. for (int j = 0; j < trainingClusters.clusterPoints[i].length; j++) { if (trainingClusters.clusterPoints[i][j][labelIndex].toInt() != maxIdx) { trainingErrors++; } } } // This should be zero. print('trainingErrors: $trainingErrors'); // A copy of the clustering that ignores the labels. final Clusters ignoreLabel = Clusters( trainingClusters.points, <int>[labelIndex], trainingClusters.clusters, trainingClusters.means, ); // Find the predicted cluster for the other half of the data. final List<List<double>> data = reader.data.sublist(trainingSetSize); final List<int> predictions = data.map((List<double> point) { return ignoreLabel.kNearestNeighbors(point, 5); }).toList(); // Count the number points where the predicted cluster doesn't match the // label. int errors = 0; for (int i = 0; i < predictions.length; i++) { final List<double> rep = ignoreLabel.clusterPoints[predictions[i]][0]; final int repClass = rep[labelIndex].toInt(); final int dataClass = data[i][labelIndex].toInt(); if (dataClass != repClass) { errors++; } } // Hopefully these are small. final int testSetSize = reader.data.length - trainingSetSize; final double errorRate = errors.toDouble() / testSetSize.toDouble(); print('classification errors: $errors / $testSetSize'); print('error rate: $errorRate'); }
zanderso/kmeans.dart
10
A Dart library for k-means clustering
Dart
zanderso
Zachary Anderson
Google
lib/kmeans.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// A Dart library for k-means calculations. library kmeans; export 'src/kmeans_base.dart';
zanderso/kmeans.dart
10
A Dart library for k-means clustering
Dart
zanderso
Zachary Anderson
Google
lib/src/kmeans_base.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; /// This class describes a clustering. class Clusters { Clusters(this.points, this.ignoredDims, this.clusters, this.means); /// The list of all points in the clusters. final List<List<double>> points; /// Dimensions of [points] that are ignored. final List<int> ignoredDims; /// For each point `points[i]`, `clusters[i]` gives the index of the cluster /// that `points[i]` is a member of. The mean of the cluster is given by /// `means[clusters[i]]`. final List<int> clusters; /// The means of the clusters. final List<List<double>> means; /// Convenience getter for the number of clusters. int get k => means.length; /// For each cluster, the list of points belonging to that cluster. /// /// `clusterPoints[i]` gives the list of points belonging to the cluster with /// mean `means[i]`. late final List<List<List<double>>> clusterPoints = (() { final List<List<List<double>>> cp = List<List<List<double>>>.generate( means.length, (int i) => <List<double>>[], ); for (int i = 0; i < points.length; i++) { cp[clusters[i]].add(points[i]); } return cp; })(); /// Sum of squared distances of samples to their closest cluster center. late final double inertia = (() { double sum = 0.0; for (int i = 0; i < points.length; i++) { sum += _distSquared(points[i], means[clusters[i]], ignoredDims); } return sum; })(); /// Computes the average 'silhouette' over all points. /// /// The higher the silhouette the better the clustering. /// /// This uses an exact computation of the silhouette of each point as defined /// in https://en.wikipedia.org/wiki/Silhouette_(clustering). late final double exactSilhouette = (() { // For each point and each cluster calculate the mean squared distance of // the point to each point in the cluster. final List<List<double>> meanClusterDist = List<List<double>>.generate( means.length, (int i) { return List<double>.filled(points.length, 0.0); }, ); for (int k = 0; k < means.length; k++) { for (int i = 0; i < points.length; i++) { double distSum = 0.0; for (int j = 0; j < clusterPoints[k].length; j++) { distSum += _distSquared(points[i], clusterPoints[k][j], ignoredDims); } meanClusterDist[k][i] = clusterPoints[k].length > 1 ? distSum / (clusterPoints[k].length - 1).toDouble() : distSum; } } // For each point find the minimum mean squared distance to a neighbor // cluster. final List<double> minNeighborDist = List<double>.filled( points.length, 0.0, ); for (int i = 0; i < points.length; i++) { double min = double.maxFinite; for (int j = 0; j < means.length; j++) { if (j != clusters[i] && meanClusterDist[j][i] < min) { min = meanClusterDist[j][i]; } } minNeighborDist[i] = min; } // Find the 'silhouette' of each point. final List<double> silhouettes = List<double>.filled(points.length, 0.0); for (int i = 0; i < points.length; i++) { final int c = clusters[i]; silhouettes[i] = clusterPoints[c].length > 1 ? (minNeighborDist[i] - meanClusterDist[c][i]) / max(minNeighborDist[i], meanClusterDist[c][i]) : 0.0; } // Return the average silhouette. double silhouetteSum = 0.0; for (int i = 0; i < points.length; i++) { silhouetteSum += silhouettes[i]; } return silhouetteSum / points.length.toDouble(); })(); /// Computes an approximation of the average 'silhouette' over all points. /// /// The higher the silhouette the better the clustering. /// /// When needed in the silhouette computation, instead of calculating the /// average distance of each point to all points in a cluster, this /// approximation calculates the average distance to a random subset of at /// most 100 points in a cluster. /// /// See: https://en.wikipedia.org/wiki/Silhouette_(clustering). late final double silhouette = (() { final Random rng = Random(100); // For each point find the mean distance over all points in the nearest // neighbor cluster. final List<double> minNeighborDist = List<double>.filled( points.length, 0.0, ); for (int i = 0; i < points.length; i++) { double minDist = double.maxFinite; int minNeighborK = -1; for (int k = 0; k < means.length; k++) { if (clusters[i] == k) { continue; } final double d = _distSquared(points[i], means[k], ignoredDims); if (d < minDist) { minDist = d; minNeighborK = k; } } // If the size of the cluster is over some threshold, then // sample the points isntead of summing all of them. final List<List<double>> cluster = clusterPoints[minNeighborK]; final int neighborSize = cluster.length; if (neighborSize <= 100) { double sum = 0.0; for (int j = 0; j < cluster.length; j++) { sum += _distSquared(points[i], cluster[j], ignoredDims); } minNeighborDist[i] = sum / cluster.length.toDouble(); } else { // 100 samples. double sum = 0.0; for (int j = 0; j < 100; j++) { final int sample = rng.nextInt(neighborSize); sum += _distSquared(points[i], cluster[sample], ignoredDims); } minNeighborDist[i] = sum / 100.0; } } // For each point find the mean distance over all points in the same // cluster. final List<double> meanClusterDist = List<double>.filled( points.length, 0.0, ); for (int i = 0; i < points.length; i++) { // If the size of the cluster is over some threshold, then // sample the points isntead of summing all of them. final int k = clusters[i]; final int clusterSize = clusterPoints[k].length; if (clusterSize <= 100) { double sum = 0.0; for (int j = 0; j < clusterPoints[k].length; j++) { sum += _distSquared(points[i], clusterPoints[k][j], ignoredDims); } meanClusterDist[i] = clusterPoints[k].length > 1 ? sum / (clusterPoints[k].length - 1).toDouble() : sum; } else { double sum = 0.0; for (int j = 0; j < 100; j++) { final int sample = rng.nextInt(clusterSize); sum += _distSquared(points[i], clusterPoints[k][sample], ignoredDims); } meanClusterDist[i] = sum / 100; } } // Find the 'silhouette' of each point. final List<double> silhouettes = List<double>.filled(points.length, 0.0); for (int i = 0; i < points.length; i++) { final int c = clusters[i]; silhouettes[i] = clusterPoints[c].length > 1 ? (minNeighborDist[i] - meanClusterDist[i]) / max(minNeighborDist[i], meanClusterDist[i]) : 0.0; } // Return the average silhouette. double silhouetteSum = 0.0; for (int i = 0; i < points.length; i++) { silhouetteSum += silhouettes[i]; } return silhouetteSum / points.length.toDouble(); })(); /// Returns the index of the mean that is closest to `point`. int nearestMean(List<double> point) { double minDist = double.maxFinite; int minK = -1; for (int j = 0; j < means.length; j++) { final double dist = _distSquared(point, means[j], ignoredDims); if (dist < minDist) { minDist = dist; minK = j; } } return minK; } /// Predict the cluster that `point` belongs to by way of a vote among its /// `k` nearest neighbors. /// /// This can be an expensive calculation, as it calculates the distnace to /// every point in every cluster in order to find the nearest `k`. /// /// https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm int kNearestNeighbors(List<double> point, int k) { final List<MapEntry<double, int>> neighbors = List<MapEntry<double, int>>.generate( k, (int idx) { return const MapEntry<double, int>(double.maxFinite, -1); }, ); for (int i = 0; i < points.length; i++) { final double dist = _distSquared(point, points[i], ignoredDims); if (dist < neighbors[k - 1].key) { neighbors.add(MapEntry<double, int>(dist, clusters[i])); neighbors.sort((MapEntry<double, int> a, MapEntry<double, int> b) { return a.key.compareTo(b.key); }); neighbors.removeLast(); } } // Add 1/d for each point at distance d to the accumulator for its cluster. final List<double> neighborCounts = List<double>.filled(means.length, 0.0); for (int i = 0; i < k; i++) { neighborCounts[neighbors[i].value] += 1.0 / neighbors[i].key; } // Find the cluster with the largest value. double maxCount = 0.0; int maxIdx = -1; for (int i = 0; i < neighborCounts.length; i++) { if (neighborCounts[i] > maxCount) { maxCount = neighborCounts[i]; maxIdx = i; } } return maxIdx; } @override String toString() { final StringBuffer buf = StringBuffer(); buf.writeln('K: $k'); buf.writeln('Means:'); for (int i = 0; i < means.length; i++) { buf.writeln(means[i]); } buf.writeln(''); buf.writeln('Inertia: $inertia'); buf.writeln('Silhouette: $silhouette'); buf.writeln('Exact Silhouette: $exactSilhouette'); buf.writeln(''); buf.writeln('Points'); for (int i = 0; i < points.length; i++) { buf.writeln('${points[i]} -> ${clusters[i]}'); } return buf.toString(); } } /// The type of the function used by the k-means algorithm to select the /// initial set of cluster centers. typedef KMeansInitializer = List<List<double>> Function( List<List<double>> points, List<int> ignoreDims, int k, int seed, ); /// A collection of methods for calculating initial means. class KMeansInitializers { KMeansInitializers._(); /// Returns an initial set of k means initialized according to the k-means++ /// algorithm: /// https://en.wikipedia.org/wiki/K-means%2B%2B static List<List<double>> kMeansPlusPlus( List<List<double>> points, List<int> ignoredDims, int k, int seed, ) { final Random rng = Random(seed); final int dim = points[0].length; final List<List<double>> means = List<List<double>>.generate(k, (int i) { return List<double>.filled(dim, 0.0); }); means[0] = points[rng.nextInt(points.length)]; for (int i = 1; i < k; i++) { final List<double> ds = points.map((List<double> p) { double minDist = double.maxFinite; for (int j = 0; j < i; j++) { final double d = _distSquared(means[j], p, ignoredDims); if (d < minDist) { minDist = d; } } return minDist; }).toList(); final double sum = ds.fold(0.0, (double a, double b) => a + b); final List<double> ps = ds.map((double x) => x / sum).toList(); int pointIndex = 0; final double r = rng.nextDouble(); double cum = 0.0; while (true) { cum += ps[pointIndex]; if (cum > r) { break; } pointIndex++; } means[i] = points[pointIndex]; } return means; } /// Returns an initial set of `k` cluster centers randomly selected from /// `points`. static List<List<double>> random( List<List<double>> points, List<int> ignoredDims, int k, int seed, ) { final Random rng = Random(seed); final List<List<double>> means = List<List<double>>.generate( k, (int i) { return List<double>.filled(points[0].length, 0.0); }, ); final List<int> selectedIndices = <int>[]; for (int i = 0; i < k; i++) { int next = 0; do { next = rng.nextInt(points.length); } while (selectedIndices.contains(next)); selectedIndices.add(next); means[i] = points[next]; } return means; } /// Returns a cluster initializer function that simply returns `means`. static KMeansInitializer fromArray(List<List<double>> means) { return (List<List<double>> points, List<int> ignoreDims, int k, int seed) { return means; }; } } /// A class for organizing k-means computations with utility methods for /// finding a good solution. /// /// https://en.wikipedia.org/wiki/K-means_clustering /// /// Uses k-means++ (https://en.wikipedia.org/wiki/K-means%2B%2B) for the /// initial means, and then iterates. /// /// The points accepted by [KMeans] can have any number of dimensions and are /// represented by `List<double>`. The distance function is hard-coded to be /// the euclidan distance. class KMeans { /// [points] gives the list of points to cluster. [ignoreDims] gives a list /// of dimensions of [points] to ignore. [labelDim] gives the index of a /// label in each point if there is one. KMeans( this.points, { this.ignoredDims = _emptyList, this.labelDim = -1, }) { // Translate points so that the range in each dimension is centered at 0, // and scale each point so that the range in each dimension is the same // as the largest range of a dimension in [points]. final int dims = points[0].length; _scaledPoints = List<List<double>>.generate(points.length, (int i) { return List<double>.filled(dims, 0.0); }); // Find the largest range in each dimension. final List<double> mins = List<double>.filled(dims, double.maxFinite); final List<double> maxs = List<double>.filled(dims, -double.maxFinite); for (int i = 0; i < points.length; i++) { for (int j = 0; j < dims; j++) { if (points[i][j] < mins[j]) { mins[j] = points[i][j]; } if (points[i][j] > maxs[j]) { maxs[j] = points[i][j]; } } } final List<double> ranges = List<double>.generate(dims, (int i) { return maxs[i] - mins[i]; }); double maxRange = -double.maxFinite; for (int i = 0; i < dims; i++) { if (i == labelDim) { continue; } if (ranges[i] > maxRange) { maxRange = ranges[i]; } } _translations = List<double>.filled(dims, 0.0); _scales = List<double>.filled(dims, 0.0); for (int i = 0; i < dims; i++) { _translations[i] = mins[i] + ranges[i] / 2.0; _scales[i] = i == labelDim ? maxRange * 10.0 : maxRange / ranges[i]; } for (int i = 0; i < points.length; i++) { for (int j = 0; j < dims; j++) { _scaledPoints[i][j] = (points[i][j] - _translations[j]) * _scales[j]; } } } /// Numbers closer together than this are considered equivalent. static const double defaultPrecision = 1e-4; static const List<int> _emptyList = <int>[]; /// The points to cluster. final List<List<double>> points; /// Dimensions of [points] that are ignored. final List<int> ignoredDims; /// The index of the label. Defaults to `-1` if the data is unlabeled. final int labelDim; // The translation to apply to each dimension. late final List<double> _translations; // The scaling to apply in each dimension. late final List<double> _scales; // The points after translating and scaling. late final List<List<double>> _scaledPoints; /// Returns a [Cluster] of [points] into [k] clusters. Clusters fit( int k, { int maxIterations = 300, int seed = 42, KMeansInitializer init = KMeansInitializers.kMeansPlusPlus, double tolerance = defaultPrecision, }) { final List<int> clusters = List<int>.filled(_scaledPoints.length, 0); final List<List<double>> means = init(_scaledPoints, ignoredDims, k, seed); for (int iters = 0; iters < maxIterations; iters++) { // Put points into the closest cluster. _populateClusters(means, clusters); // Shift means. if (!_shiftClusters(clusters, means, tolerance)) { break; } if (iters == maxIterations - 1) { print('Reached max iters!'); } } final List<List<double>> descaledMeans = List<List<double>>.generate( means.length, (int i) { return List<double>.generate(means[0].length, (int j) { return means[i][j] / _scales[j] + _translations[j]; }); }, ); return Clusters(points, ignoredDims, clusters, descaledMeans); } /// Finds the 'best' k-means [Cluster] over a range of possible values of /// 'k'. /// /// Returns the clustering whose 'k' maximmizes the average 'silhouette' /// (https://en.wikipedia.org/wiki/Silhouette_(clustering)). Clusters bestFit({ int maxIterations = 300, int seed = 42, int minK = 2, int maxK = 20, int trialsPerK = 1, KMeansInitializer init = KMeansInitializers.kMeansPlusPlus, double tolerance = defaultPrecision, bool useExactSilhouette = false, }) { Clusters? best; int k = minK; int trial = 0; while (k <= maxK && k <= _scaledPoints.length) { final Clusters km = fit( k, maxIterations: maxIterations, seed: seed + trial, init: init, tolerance: tolerance, ); if (useExactSilhouette) { if (best == null || km.exactSilhouette > best.exactSilhouette) { best = km; } } else { if (best == null || km.silhouette > best.silhouette) { best = km; } } trial++; if (trial == trialsPerK) { k++; trial = 0; } } return best!; } // Put points into the closest cluster. void _populateClusters(List<List<double>> means, List<int> outClusters) { for (int i = 0; i < _scaledPoints.length; i++) { int kidx = 0; double kdist = _distSquared(_scaledPoints[i], means[0], ignoredDims); for (int j = 1; j < means.length; j++) { final double dist = _distSquared(_scaledPoints[i], means[j], ignoredDims); if (dist < kdist) { kidx = j; kdist = dist; } } outClusters[i] = kidx; } } // Shift cluster means. bool _shiftClusters( List<int> clusters, List<List<double>> means, double tolerance, ) { bool shifted = false; final int dim = means[0].length; for (int i = 0; i < means.length; i++) { final List<double> newMean = List<double>.filled(dim, 0.0); double n = 0.0; for (int j = 0; j < _scaledPoints.length; j++) { // TODO(zra): Only iterate over the points in the right cluster. if (clusters[j] != i) { continue; } for (int m = 0; m < dim; m++) { if (ignoredDims.contains(m)) { continue; } newMean[m] = (newMean[m] * n + _scaledPoints[j][m]) / (n + 1.0); } n += 1.0; } for (int m = 0; m < dim; m++) { if (ignoredDims.contains(m)) { continue; } if ((means[i][m] - newMean[m]).abs() > tolerance) { shifted = true; break; } } means[i] = newMean; } return shifted; } } double _distSquared(List<double> a, List<double> b, List<int> ignoredDims) { assert(a.length == b.length); final int length = a.length; double sum = 0.0; for (int i = 0; i < length; i++) { if (ignoredDims.contains(i)) { continue; } final double diff = a[i] - b[i]; final double diffSquared = diff * diff; sum += diffSquared; } return sum; }
zanderso/kmeans.dart
10
A Dart library for k-means clustering
Dart
zanderso
Zachary Anderson
Google
test/kmeans_test.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'dart:math'; import 'package:kmeans/kmeans.dart'; import 'package:test/test.dart'; import 'utils/arff.dart'; void main() { test('KMeans sanity check', () { final List<List<double>> points = <List<double>>[ <double>[0.9], <double>[1.0], <double>[1.1], <double>[1.9], <double>[2.0], <double>[2.1], ]; final KMeans kmeans = KMeans(points); final Clusters k = kmeans.fit(2); expect(k.k, equals(2)); expect(k.means.length, equals(2)); expect(k.means[0] != k.means[1], isTrue); expect(k.clusters[0] == k.clusters[1], isTrue); expect(k.clusters[1] == k.clusters[2], isTrue); expect(k.clusters[2] != k.clusters[3], isTrue); expect(k.clusters[3] == k.clusters[4], isTrue); expect(k.clusters[4] == k.clusters[5], isTrue); expect(k.clusterPoints[0].length, equals(3)); expect(k.clusterPoints[1].length, equals(3)); expect( (k.inertia - 0.04).abs(), lessThanOrEqualTo(KMeans.defaultPrecision)); expect( <List<double>>[ <double>[k.means[0][0] + 0.05] ].map(k.nearestMean), equals(<int>[0])); expect( <List<double>>[ <double>[k.means[1][0] + 0.05] ].map(k.nearestMean), equals(<int>[1])); }); test('Best KMeans sanity check', () { final List<List<double>> points = <List<double>>[ <double>[0.9], <double>[1.0], <double>[1.1], <double>[1.9], <double>[2.0], <double>[2.1], <double>[2.9], <double>[3.0], <double>[3.1], ]; final KMeans kmeans = KMeans(points); final Clusters k = kmeans.bestFit(); expect(k.k, equals(3)); expect(k.means.length, equals(3)); expect(k.means[0] != k.means[1], isTrue); expect(k.means[1] != k.means[2], isTrue); expect(k.clusters[0] == k.clusters[1], isTrue); expect(k.clusters[1] == k.clusters[2], isTrue); expect(k.clusters[2] != k.clusters[3], isTrue); expect(k.clusters[3] == k.clusters[4], isTrue); expect(k.clusters[4] == k.clusters[5], isTrue); expect(k.clusters[5] != k.clusters[6], isTrue); expect(k.clusters[6] == k.clusters[7], isTrue); expect(k.clusters[7] == k.clusters[8], isTrue); expect(k.clusterPoints[0].length, equals(3)); expect(k.clusterPoints[1].length, equals(3)); expect(k.clusterPoints[2].length, equals(3)); expect( (k.inertia - 0.06).abs(), lessThanOrEqualTo(KMeans.defaultPrecision)); expect( <List<double>>[ <double>[k.means[0][0] + 0.05], <double>[k.means[1][0] + 0.05], <double>[k.means[2][0] + 0.05], ].map(k.nearestMean), equals(<int>[0, 1, 2]), ); }); List<List<double>> initializePoints( int clusters, int pointsPerCluster, double maxX, double maxY, Random rng, ) { final List<Point<double>> means = List<Point<double>>.generate( clusters, (int i) { return Point<double>( rng.nextDouble() * 1000.0, rng.nextDouble() * 1000.0, ); }, ); final List<double> sds = List<double>.generate(clusters, (int i) { return rng.nextDouble(); }); double nextGaussian() { double v1, v2, s; do { v1 = 2.0 * rng.nextDouble() - 1.0; v2 = 2.0 * rng.nextDouble() - 1.0; s = v1 * v1 + v2 * v2; } while (s >= 1.0 || s == 0.0); s = sqrt(-2.0 * log(s) / s); return v1 * s; } final List<List<double>> points = <List<double>>[]; for (int i = 0; i < clusters * pointsPerCluster; i++) { final int cluster = i ~/ pointsPerCluster; final Point<double> mean = means[cluster]; final double sd = sds[cluster]; final double x = mean.x + nextGaussian() * sd; final double y = mean.y + nextGaussian() * sd; points.add(<double>[x, y]); } return points; } test('Generated clusters best k-means finds the right k', () { const int minK = 2; const int maxK = 15; const int pointsPerCluster = 100; final Random rng = Random(42); for (int clusters = minK; clusters < maxK; clusters++) { final List<List<double>> points = initializePoints( clusters, pointsPerCluster, 1000.0, 1000.0, rng, ); final KMeans kmeans = KMeans(points); final Clusters k = kmeans.bestFit( minK: minK, maxK: maxK, ); // We found the right k. expect(k.k, equals(clusters)); expect(k.means.length, equals(clusters)); } }); test('The approximate silhouette is close to the exact silhouette', () { const int minK = 2; const int maxK = 10; const int pointsPerCluster = 200; final Random rng = Random(42); for (int clusters = minK; clusters <= maxK; clusters++) { final List<List<double>> points = initializePoints( clusters, pointsPerCluster, 1000.0, 1000.0, rng, ); final KMeans kmeans = KMeans(points); for (int i = minK; i <= maxK; i++) { final Clusters c = kmeans.fit(i); expect((c.silhouette - c.exactSilhouette).abs(), lessThan(0.02)); } } }); test2DArff( fileName: '2d-10c', k: 9, minK: 2, maxK: 15, trials: 3, errors: 5, ); test2DArff( fileName: '2d-20c-no0', k: 20, minK: 18, maxK: 21, trials: 100, errors: 50, ); test2DArff( fileName: '2d-4c-no9', k: 4, minK: 2, maxK: 6, errors: 60, trials: 1, ); } void test2DArff({ required String fileName, required int k, required int errors, required int minK, required int maxK, required int trials, }) { test('$fileName with labels', () async { final ArffReader reader = ArffReader.fromFile(File('test/data/$fileName.arff')); await reader.parse(); // The third dimension is the label. Exagerate it to test that bestFit is // finding the right number of clusters and getting all the right points // into those clusters. for (int i = 0; i < reader.data.length; i++) { reader.data[i][2] *= 1e6; } final KMeans kmeans = KMeans(reader.data, ignoredDims: <int>[]); final Clusters clusters = kmeans.bestFit( minK: minK, maxK: maxK, trialsPerK: trials, ); expect(clusters.k, equals(k)); // The third dimension of each point gives the actual cluster. Check that // all points we clustered together should really be together. for (int i = 0; i < clusters.clusterPoints.length; i++) { final double c = clusters.clusterPoints[i][0][2]; for (int j = 0; j < clusters.clusterPoints[i].length; j++) { expect(clusters.clusterPoints[i][j][2], equals(c)); } } }); test('$fileName without labels', () async { final ArffReader reader = ArffReader.fromFile(File('test/data/$fileName.arff')); await reader.parse(); // Ignore the third dimension of each point. It is the label, which we // leave off now, and then check later. final KMeans kmeans = KMeans(reader.data, ignoredDims: <int>[2]); final Clusters clusters = kmeans.bestFit( minK: minK, maxK: maxK, trialsPerK: trials, ); expect(clusters.k, equals(k)); // May get a few wrong. int errors = 0; for (int i = 0; i < clusters.clusterPoints.length; i++) { final List<int> counts = List<int>.filled(clusters.k + 1, 0); for (int j = 0; j < clusters.clusterPoints[i].length; j++) { counts[clusters.clusterPoints[i][j][2].toInt()]++; } int maxIdx = -1; int maxCount = 0; for (int j = 0; j < clusters.k + 1; j++) { if (counts[j] > maxCount) { maxCount = counts[j]; maxIdx = j; } } // If a point isn't in the maxIdx cluster, consider it an error. for (int j = 0; j < clusters.clusterPoints[i].length; j++) { if (clusters.clusterPoints[i][j][2].toInt() != maxIdx) { errors++; } } } expect(errors, lessThanOrEqualTo(errors)); }); }
zanderso/kmeans.dart
10
A Dart library for k-means clustering
Dart
zanderso
Zachary Anderson
Google
test/utils/arff.dart
Dart
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; class ArffReader { ArffReader.fromFile(File f) : _dataStream = f.openRead(); ArffReader.fromStream(this._dataStream); final Stream<List<int>> _dataStream; List<List<double>> get data => _data; late List<List<double>> _data; Future<void> parse() async { final List<List<double>> dataList = <List<double>>[]; bool parsingData = false; final Stream<String> lineStream = _dataStream.transform(utf8.decoder).transform(const LineSplitter()); await for (final String l in lineStream) { final String line = l.trim(); if (line.startsWith('%')) { continue; } if (line.contains('@data') || line.contains('@DATA')) { parsingData = true; continue; } if (!parsingData) { continue; } final List<String> sampleStrings = line.split(','); final List<double> sampleNumbers = sampleStrings.map((String d) { return double.tryParse(d) ?? _stringTableIndex(d).toDouble(); }).toList(); dataList.add(sampleNumbers); } _data = dataList; } final Map<String, int> _stringTable = <String, int>{}; int _stringTableIndex(String s) { final int length = _stringTable.length; return _stringTable.putIfAbsent(s, () => length); } }
zanderso/kmeans.dart
10
A Dart library for k-means clustering
Dart
zanderso
Zachary Anderson
Google
android/app/build.gradle
Gradle
def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion flutter.compileSdkVersion ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "dev.flutter.spendy_rasters" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
android/app/src/main/kotlin/dev/flutter/spendy_rasters/MainActivity.kt
Kotlin
package dev.flutter.spendy_rasters import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
android/build.gradle
Gradle
buildscript { ext.kotlin_version = '1.7.10' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.2.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
android/settings.gradle
Gradle
include ':app' def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties() assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
ios/Runner/AppDelegate.swift
Swift
import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
ios/Runner/Runner-Bridging-Header.h
C/C++ Header
#import "GeneratedPluginRegistrant.h"
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
lib/main.dart
Dart
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart' as svg; const int kStarPoints = 48; // Number of points on the star-shaped clips. // higher -> slower const int kStarLayers = 10; // Number of star-shaped clips stacked up. // higher -> slower const int kTigerColumns = 1; // Number of tigers per column in the scroll view // grid. // higher -> slower const int kSpinDuration = 5; // Tiger rotation period in seconds. // lower -> faster spinning void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Flutter Demo', home: Scaffold( body: Center( child: PainfulTigerGrid(count: 200), ), ), ); } } class PainfulAnimation extends StatefulWidget { const PainfulAnimation({ super.key, required this.child, }); final Widget child; @override State<PainfulAnimation> createState() => PainfulAnimationState(); } class PainfulAnimationState extends State<PainfulAnimation> with TickerProviderStateMixin { late AnimationController _rotationController; @override void initState() { super.initState(); _rotationController = AnimationController( vsync: this, duration: const Duration(seconds: kSpinDuration), ) ..repeat(); } @override void dispose() { _rotationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { Widget result = RotationTransition( turns: _rotationController, child: widget.child, ); for (int i = 0; i < kStarLayers; i++) { result = ClipPath( clipper: StarClipper( kStarPoints, outerScale: 1.05 + 0.05 * i, innerScale: 0.60, ), child: Container( color: i % 2 == 0 ? Colors.black : Colors.orange, child: result, ) ); } return result; } } class PainfulTiger extends StatelessWidget { const PainfulTiger({ super.key, }); @override Widget build(BuildContext context) { return PainfulAnimation( child: svg.SvgPicture.asset( 'assets/tiger.svg', ), ); } } class PainfulTigerGrid extends StatelessWidget { const PainfulTigerGrid({ super.key, required this.count, }); final int count; @override Widget build(BuildContext context) { return CustomScrollView( slivers: <Widget>[ SliverGrid( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: kTigerColumns, childAspectRatio: 1.0, mainAxisSpacing: 0.0 ), delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return const PainfulTiger(); }, childCount: count, ), ), ], ); } } class StarClipper extends CustomClipper<Path> { StarClipper( this.points, { this.degreesOffset = 0.0, this.outerScale = 1.0, this.innerScale = 0.5, }); /// The number of points of the star final int points; final double degreesOffset; final double outerScale; final double innerScale; // Degrees to radians conversion double _degreeToRadian(double deg) => deg * (math.pi / 180.0); @override Path getClip(Size size) { final Path path = Path(); final double max = 2 * math.pi + _degreeToRadian(degreesOffset); final double width = size.width; final double halfWidth = width / 2; final double wingRadius = halfWidth * outerScale; final double radius = halfWidth * innerScale; final double degreesPerStep = _degreeToRadian(360 / points); final double halfDegreesPerStep = degreesPerStep / 2; final startStep = _degreeToRadian(degreesOffset); path.moveTo( halfWidth + radius * math.cos(startStep), halfWidth + radius * math.sin(startStep), ); for (double step = startStep; step < max; step += degreesPerStep) { path.quadraticBezierTo( halfWidth + wingRadius * math.cos(step + halfDegreesPerStep), halfWidth + wingRadius * math.sin(step + halfDegreesPerStep), halfWidth + radius * math.cos(step + degreesPerStep), halfWidth + radius * math.sin(step + degreesPerStep), ); } path.close(); return path; } // If the new instance represents different information than the old instance, // this method will return true, otherwise it should return false. @override bool shouldReclip(CustomClipper<Path> oldClipper) { StarClipper starClipper = oldClipper as StarClipper; return points != starClipper.points || degreesOffset != starClipper.degreesOffset || innerScale != starClipper.innerScale || outerScale != starClipper.outerScale; } }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
macos/Flutter/GeneratedPluginRegistrant.swift
Swift
// // Generated file. Do not edit. // import FlutterMacOS import Foundation func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
macos/Runner/AppDelegate.swift
Swift
import Cocoa import FlutterMacOS @NSApplicationMain class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
macos/Runner/MainFlutterWindow.swift
Swift
import Cocoa import FlutterMacOS class MainFlutterWindow: NSWindow { override func awakeFromNib() { let flutterViewController = FlutterViewController.init() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) super.awakeFromNib() } }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
test/widget_test.dart
Dart
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:spendy_rasters/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
zanderso/spendy_rasters
2
Experimental Flutter app for exploring expensive rasterization.
Dart
zanderso
Zachary Anderson
Google
lib/bin.js
JavaScript
#!/usr/bin/env node const {downloadAndPackageModule} = require('./index') if (process.argv.length < 3) { console.log('Usage: standmo [--bin] module[@version]...') process.exit(2) } const fromBin = process.argv.includes('--bin') for (const arg of process.argv.slice(2)) { if (arg.startsWith('--')) continue downloadAndPackageModule(arg, {fromBin}).catch(error => { console.error(error) process.exit(1) }) }
zcbenz/stanmo
2
Generate standalone bundles for Node.js modules
JavaScript
zcbenz
Cheng
Apple
lib/index.js
JavaScript
const fs = require('fs') const path = require('path') const execa = require('execa') const useTmpDir = require('@m59/use-tmp-dir') const terser = require('terser') async function downloadAndPackageModule(name, options={fromBin: false}) { await useTmpDir(async tempDir => { await downloadModule(tempDir, name) await packageModule(tempDir, options) }) } async function downloadModule(dir, name) { try { await execa('npm', ['install', '--global-style', name], {cwd: dir}) } catch (error) { throw new Error('Failed to install module:\n' + error.stderr) } } async function packageModule(parentDir, options) { const modulesDir = path.join(parentDir, 'node_modules') const ignoreFiles = ['.bin', '.package-lock.json'] const dirs = fs.readdirSync(modulesDir).filter((d) => !ignoreFiles.includes(d)) if (dirs.length !== 1) throw new Error(`Multiple modules installed while there should only be one: ${dirs}`) let moduleName = dirs[0] let moduleDir = path.join(modulesDir, moduleName) if (moduleName.startsWith('@')) { moduleName = fs.readdirSync(moduleDir)[0] moduleDir = path.join(moduleDir, moduleName) } const packageJson = JSON.parse(fs.readFileSync(path.join(moduleDir, 'package.json'))) if (options.fromBin) { if (!packageJson.bin) throw new Error('package.json file does not have "bin" field') if (typeof packageJson.bin === 'string') { await packageFile(packageJson, moduleDir, moduleName, path.join(moduleDir, packageJson.bin)) } else if (typeof packageJson.bin === 'object') { for (const name in packageJson.bin) await packageFile(packageJson, moduleDir, name, path.join(moduleDir, packageJson.bin[name])) } else { throw new Error(`Unrecognized "bin" field: ${packageJson.bin}`) } } else { await packageFile(packageJson, moduleDir, moduleName, require.resolve(moduleDir)) } } async function packageFile(packageJson, dir, name, file) { const content = await runBrowserify(name, file) const result = await terser.minify(content) if (result.error) throw new Error(`Failed to minify code: ${result.error.message}`) const finalContent = await addInfo(packageJson, dir, result.code) fs.writeFileSync(name + '.js', finalContent) } async function runBrowserify(moduleName, moduleFile) { try { const {stdout} = await execa('browserify', [ '--standalone', moduleName, '--node', '--ignore-missing', moduleFile, ]) return stdout } catch (error) { throw new Error('Failed to browserify module:\n' + error.stderr) } } async function addInfo(packageJson, dir, content) { let license = `License: ${packageJson.license}` const possibleLicenses = ['LICENSE', 'license', 'License', 'License.md'] for (const l of possibleLicenses) { const p = path.join(dir, l) if (fs.existsSync(p)) license = fs.readFileSync(p).toString() } license = license.split('\n').map(l => ('// ' + l).trim()).join('\n') const comment = `// ${packageJson.name}@${packageJson.version}\n//\n${license}\n` return comment + content } module.exports = {downloadAndPackageModule}
zcbenz/stanmo
2
Generate standalone bundles for Node.js modules
JavaScript
zcbenz
Cheng
Apple
bin/sweet-sweet-opencode.js
JavaScript
#!/usr/bin/env node /* eslint-disable no-console */ const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const readline = require("node:readline"); const { spawnSync } = require("node:child_process"); const BLOG_URL = "https://zeke.sikelianos.com/building-on-cloudflare/"; const DEFAULT_CONFIG = { $schema: "https://opencode.ai/config.json", mcp: { "chrome-devtools": { type: "local", command: ["npx", "-y", "chrome-devtools-mcp@latest"] }, "cloudflare-docs": { type: "remote", url: "https://docs.mcp.cloudflare.com/mcp", enabled: true }, "replicate-code-mode": { type: "local", enabled: false, command: ["npx", "-y", "replicate-mcp@alpha", "--tools=code"], environment: { REPLICATE_API_TOKEN: "{env:REPLICATE_API_TOKEN}" } }, "cloudflare-api": { type: "remote", enabled: false, url: "https://cloudflare-mcp.mattzcarey.workers.dev/mcp", headers: { Authorization: "Bearer {env:CLOUDFLARE_API_TOKEN}" } } } }; function parseArgs(argv) { const args = new Set(argv.slice(2)); return { yes: args.has("--yes") || args.has("-y"), dryRun: args.has("--dry-run") }; } function printHeader() { console.log("\nSweet Sweet OpenCode (Cloudflare setup)\n"); console.log(`This sets up OpenCode + Cloudflare MCP as described in: ${BLOG_URL}`); console.log("\nFlags: --yes (auto-accept), --dry-run (print only)\n"); } function commandExists(cmd) { const which = process.platform === "win32" ? "where" : "command"; const args = process.platform === "win32" ? [cmd] : ["-v", cmd]; const res = spawnSync(which, args, { stdio: "ignore" }); return res.status === 0; } function runCommand(command, args, { dryRun } = {}) { const printable = [command, ...args].join(" "); console.log(`\n> ${printable}`); if (dryRun) return { status: 0 }; const res = spawnSync(command, args, { stdio: "inherit" }); return res; } function mkdirp(dirPath) { fs.mkdirSync(dirPath, { recursive: true }); } function readJsonIfExists(filePath) { try { return JSON.parse(fs.readFileSync(filePath, "utf8")); } catch { return null; } } function stableStringify(obj) { return JSON.stringify(obj, null, 2) + "\n"; } function configPath() { const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"); return path.join(configHome, "opencode", "opencode.json"); } function createRl() { return readline.createInterface({ input: process.stdin, output: process.stdout }); } async function askConfirm(rl, message, { defaultYes = true, autoYes = false } = {}) { if (autoYes) { console.log(`${message} ${defaultYes ? "(auto: yes)" : "(auto: no)"}`); return defaultYes; } const suffix = defaultYes ? "[Y/n]" : "[y/N]"; const answer = await new Promise((resolve) => rl.question(`${message} ${suffix} `, resolve)); const normalized = String(answer || "").trim().toLowerCase(); if (!normalized) return defaultYes; if (["y", "yes"].includes(normalized)) return true; if (["n", "no"].includes(normalized)) return false; return defaultYes; } async function main() { const opts = parseArgs(process.argv); printHeader(); const rl = createRl(); try { const proceed = await askConfirm(rl, "Continue?", { autoYes: opts.yes }); if (!proceed) process.exit(0); const nodeMajor = Number(process.versions.node.split(".")[0]); if (Number.isFinite(nodeMajor) && nodeMajor < 18) { console.log(`\n! Your Node.js version is ${process.version}. This script expects Node >= 18.`); } // 1) Install OpenCode if (commandExists("opencode")) { console.log("\n- OpenCode is already installed (found `opencode` in PATH). Skipping install."); } else { console.log("\n- OpenCode is not installed."); const install = await askConfirm(rl, "Install OpenCode now?", { autoYes: opts.yes }); if (install) { if (process.platform === "darwin" && commandExists("brew")) { console.log("This will run: brew install anomalyco/tap/opencode"); const ok = await askConfirm(rl, "Run brew install?", { autoYes: opts.yes }); if (ok) { const res = runCommand("brew", ["install", "anomalyco/tap/opencode"], { dryRun: opts.dryRun }); if (res.status !== 0) process.exit(res.status || 1); } } else { console.log("\nInstall OpenCode manually, then re-run this script:"); console.log("- https://opencode.ai/docs/#install"); } } } // 2) Write global config const cfgPath = configPath(); const cfgDir = path.dirname(cfgPath); const cfgExisting = readJsonIfExists(cfgPath); const cfgDefaultStr = stableStringify(DEFAULT_CONFIG); const cfgExistingStr = cfgExisting ? stableStringify(cfgExisting) : null; console.log(`\n- OpenCode config path: ${cfgPath}`); if (cfgExistingStr === cfgDefaultStr) { console.log(" Config already matches the default. Skipping."); } else { const write = await askConfirm(rl, "Write default OpenCode config to this path?", { autoYes: opts.yes }); if (write) { if (!opts.dryRun) mkdirp(cfgDir); if (fs.existsSync(cfgPath)) { const ts = new Date().toISOString().replace(/[:.]/g, "-"); const backupPath = `${cfgPath}.bak.${ts}`; console.log(` Backing up existing config to: ${backupPath}`); if (!opts.dryRun) fs.copyFileSync(cfgPath, backupPath); } console.log(" Writing config..."); if (!opts.dryRun) fs.writeFileSync(cfgPath, cfgDefaultStr, "utf8"); } } // 3) Wrangler login if (!commandExists("npx")) { console.log("\n! `npx` not found in PATH. Install Node.js (includes npm/npx), then re-run."); } else { console.log("\n- Checking Cloudflare auth (wrangler whoami)..."); const whoami = runCommand("npx", ["-y", "wrangler", "whoami"], { dryRun: opts.dryRun }); if (whoami.status === 0) { console.log(" Wrangler is already authenticated."); } else { console.log(" Wrangler does not appear authenticated yet."); const login = await askConfirm(rl, "Run `npx -y wrangler login` now?", { autoYes: opts.yes }); if (login) { console.log("This will open a browser window for Cloudflare authorization."); const res = runCommand("npx", ["-y", "wrangler", "login"], { dryRun: opts.dryRun }); if (res.status !== 0) process.exit(res.status || 1); } } } console.log("\nDone."); console.log("\nNext:"); console.log("- Start a project folder, then run `opencode`."); console.log(" Example: mkdir my-new-app && cd my-new-app && opencode"); console.log("\nNotes:"); console.log("- `cloudflare-docs` is enabled by default."); console.log("- Extra credit: enable `replicate-code-mode` + `cloudflare-api` once you set `REPLICATE_API_TOKEN` + `CLOUDFLARE_API_TOKEN`."); } finally { rl.close(); } } main().catch((err) => { console.error(err); process.exit(1); });
zeke/sweet-sweet-opencode
19
Script that sets up OpenCode for building apps on Cloudflare and Replicate
JavaScript
zeke
Zeke Sikelianos
replicate
app/layout.tsx
TypeScript (TSX)
import "./ui/global.css"; import { Toaster } from "./ui/toaster"; export const metadata = { title: "Next.js", description: "Generated by Next.js", }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body> {children} <Toaster /> </body> </html> ); }
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
app/lib/actions.ts
TypeScript
"use server"; import { Resend } from "resend"; import { VercelInviteUserEmail } from "../../emails/vercel-invite-user"; const resend = new Resend(process.env.RESEND_API_KEY); type State = { error: string } | { data: string }; export async function send(prevState: State, formData: FormData) { const email = formData.get("email") as string; const { data, error } = await resend.emails.send({ from: "Vercel <vercel@resend.dev>", to: [email], subject: "Join team on Vercel", react: VercelInviteUserEmail({}), }); if (error) { return { error: error.message }; } console.log(data); return { data: "Email sent!" }; }
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
app/page.tsx
TypeScript (TSX)
"use client"; import clsx from "clsx"; import { useFormState, useFormStatus } from "react-dom"; import { send } from "./lib/actions"; import * as React from "react"; import { toast } from "sonner"; export default function Page() { const [state, dispatch] = useFormState(send, undefined); React.useEffect(() => { if (!state) { return; } if ("data" in state) { toast(state.data); } else if ("error" in state) { toast(`Error when sending email: ${state.error}`); } }, [state]); return ( <div className="bg-zinc-950 p-8 min-h-screen flex justify-center items-center sm:items-start sm:p-24"> <div className="mx-auto w-full max-w-5xl sm:px-6 lg:px-8"> <div className="relative isolate overflow-hidden bg-gray-900 px-6 py-24 shadow-2xl rounded-lg sm:rounded-3xl sm:px-24 xl:py-32 flex items-center flex-col"> <h2 className="max-w-2xl text-center text-3xl font-bold tracking-tight text-white sm:text-4xl"> Get invited to a team </h2> <p className="mt-2 max-w-xl text-center text-lg leading-8 text-gray-300"> Type your email address to get invited to a team. </p> <form className="mt-10 flex max-w-md gap-4 items-start w-full" action={dispatch} > <label htmlFor="email" className="sr-only"> Email address </label> <input id="email" name="email" type="email" required defaultValue="delivered@resend.dev" placeholder="jane@example.com" autoComplete="email" className="w-full rounded-md border-0 bg-white/5 px-3.5 py-2 text-white shadow-sm ring-1 ring-inset ring-white/10 focus:ring-2 focus:ring-inset focus:ring-white sm:text-sm sm:leading-6" /> <SubmitButton /> </form> <svg viewBox="0 0 1024 1024" aria-hidden="true" className="absolute left-1/2 top-1/2 -z-10 h-[64rem] w-[64rem] -translate-x-1/2" > <circle r={512} cx={512} cy={512} fill="url(#759c1415-0410-454c-8f7c-9a820de03641)" fillOpacity="0.7" /> <defs> <radialGradient r={1} cx={0} cy={0} id="759c1415-0410-454c-8f7c-9a820de03641" gradientUnits="userSpaceOnUse" gradientTransform="translate(512 512) rotate(90) scale(512)" > <stop stopColor="#7775D6" /> <stop offset={1} stopColor="#E935C1" stopOpacity={0} /> </radialGradient> </defs> </svg> </div> </div> </div> ); } function SubmitButton() { const { pending } = useFormStatus(); return ( <button type="submit" className={clsx( "flex-none rounded-md bg-white px-3.5 py-2.5 text-sm font-semibold text-gray-900 shadow-sm hover:bg-gray-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white", pending && "opacity-50 cursor-not-allowed" )} > Invite </button> ); }
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
app/ui/global.css
CSS
@tailwind base; @tailwind components; @tailwind utilities;
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
app/ui/toaster.tsx
TypeScript (TSX)
"use client"; import { Toaster as Sonner } from "sonner"; type ToasterProps = React.ComponentProps<typeof Sonner>; const Toaster = ({ ...props }: ToasterProps) => { return ( <Sonner theme="dark" className="toaster group" toastOptions={{ classNames: { toast: "group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg", description: "group-[.toast]:text-muted-foreground", }, }} {...props} /> ); }; export { Toaster };
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
emails/vercel-invite-user.tsx
TypeScript (TSX)
import { Body, Button, Container, Column, Head, Heading, Hr, Html, Img, Link, Preview, Row, Section, Text, Tailwind, } from "@react-email/components"; import * as React from "react"; interface VercelInviteUserEmailProps { username?: string; userImage?: string; invitedByUsername?: string; invitedByEmail?: string; teamName?: string; teamImage?: string; inviteLink?: string; inviteFromIp?: string; inviteFromLocation?: string; } export const VercelInviteUserEmail = ({ username = "alanturing", userImage = "https://demo.react.email/static/vercel-user.png", invitedByUsername = "Alan", invitedByEmail = "alan.turing@example.com", teamName = "Enigma", teamImage = "https://demo.react.email/static/vercel-team.png", inviteLink = "https://vercel.com/teams/invite/foo", inviteFromIp = "204.13.186.218", inviteFromLocation = "São Paulo, Brazil", }: VercelInviteUserEmailProps) => { const previewText = `Join ${invitedByUsername} on Vercel`; return ( <Html> <Head /> <Preview>{previewText}</Preview> <Tailwind> <Body className="bg-white my-auto mx-auto font-sans px-2"> <Container className="border border-solid border-[#eaeaea] rounded my-[40px] mx-auto p-[20px] max-w-[465px]"> <Section className="mt-[32px]"> <Img src="https://demo.react.email/static/vercel-logo.png" width="40" height="37" alt="Vercel" className="my-0 mx-auto" /> </Section> <Heading className="text-black text-[24px] font-normal text-center p-0 my-[30px] mx-0"> Join <strong>{teamName}</strong> on <strong>Vercel</strong> </Heading> <Text className="text-black text-[14px] leading-[24px]"> Hello {username}, </Text> <Text className="text-black text-[14px] leading-[24px]"> <strong>{invitedByUsername}</strong> ( <Link href={`mailto:${invitedByEmail}`} className="text-blue-600 no-underline" > {invitedByEmail} </Link> ) has invited you to the <strong>{teamName}</strong> team on{" "} <strong>Vercel</strong>. </Text> <Section> <Row> <Column align="right"> <Img className="rounded-full" src={userImage} width="64" height="64" /> </Column> <Column align="center"> <Img src="https://demo.react.email/static/vercel-arrow.png" width="12" height="9" alt="invited you to" /> </Column> <Column align="left"> <Img className="rounded-full" src={teamImage} width="64" height="64" /> </Column> </Row> </Section> <Section className="text-center mt-[32px] mb-[32px]"> <Button className="bg-[#000000] rounded text-white text-[12px] font-semibold no-underline text-center px-5 py-3" href={inviteLink} > Join the team </Button> </Section> <Text className="text-black text-[14px] leading-[24px]"> or copy and paste this URL into your browser:{" "} <Link href={inviteLink} className="text-blue-600 no-underline"> {inviteLink} </Link> </Text> <Hr className="border border-solid border-[#eaeaea] my-[26px] mx-0 w-full" /> <Text className="text-[#666666] text-[12px] leading-[24px]"> This invitation was intended for{" "} <span className="text-black">{username}</span>. This invite was sent from <span className="text-black">{inviteFromIp}</span>{" "} located in{" "} <span className="text-black">{inviteFromLocation}</span>. If you were not expecting this invitation, you can ignore this email. If you are concerned about your account's safety, please reply to this email to get in touch with us. </Text> </Container> </Body> </Tailwind> </Html> ); }; export default VercelInviteUserEmail;
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend
next-env.d.ts
TypeScript
/// <reference types="next" /> /// <reference types="next/image-types/global" /> // NOTE: This file should not be edited // see https://nextjs.org/docs/basic-features/typescript for more information.
zenorocha/vercel-resend-integration
3
TypeScript
zenorocha
Zeno Rocha
resend