interactive_viewer.dart 56 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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' as math;

import 'package:flutter/gestures.dart';
import 'package:flutter/physics.dart';
import 'package:vector_math/vector_math_64.dart' show Quad, Vector3, Matrix4;

import 'basic.dart';
import 'framework.dart';
import 'gesture_detector.dart';
14
import 'layout_builder.dart';
15 16
import 'ticker_provider.dart';

17 18 19 20 21 22 23 24
/// A type for widget builders that take a [Quad] of the current viewport.
///
/// See also:
///
///   * [InteractiveViewer.builder], whose builder is of this type.
///   * [WidgetBuilder], which is similar, but takes no viewport.
typedef InteractiveViewerWidgetBuilder = Widget Function(BuildContext context, Quad viewport);

25 26
/// A widget that enables pan and zoom interactions with its child.
///
27 28
/// {@youtube 560 315 https://www.youtube.com/watch?v=zrn7V3bMJvg}
///
29 30
/// The user can transform the child by dragging to pan or pinching to zoom.
///
31 32 33 34 35 36 37 38 39 40
/// By default, InteractiveViewer clips its child using [Clip.hardEdge].
/// To prevent this behavior, consider setting [clipBehavior] to [Clip.none].
/// When [clipBehavior] is [Clip.none], InteractiveViewer may draw outside of
/// its original area of the screen, such as when a child is zoomed in and
/// increases in size. However, it will not receive gestures outside of its original area.
/// To prevent dead areas where InteractiveViewer does not receive gestures,
/// don't set [clipBehavior] or be sure that the InteractiveViewer widget is the
/// size of the area that should be interactive.
///
/// See [flutter-go](https://github.com/justinmc/flutter-go) for an example of
41 42 43 44 45 46 47
/// robust positioning of an InteractiveViewer child that works for all screen
/// sizes and child sizes.
///
/// See also:
///   * The [Flutter Gallery's transformations demo](https://github.com/flutter/gallery/blob/master/lib/demos/reference/transformations_demo.dart),
///     which includes the use of InteractiveViewer.
///
48
/// {@tool dartpad --template=stateless_widget_scaffold}
49 50 51 52 53 54
/// This example shows a simple Container that can be panned and zoomed.
///
/// ```dart
/// Widget build(BuildContext context) {
///   return Center(
///     child: InteractiveViewer(
55
///       boundaryMargin: const EdgeInsets.all(20.0),
56 57 58
///       minScale: 0.1,
///       maxScale: 1.6,
///       child: Container(
59
///         decoration: const BoxDecoration(
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
///           gradient: LinearGradient(
///             begin: Alignment.topCenter,
///             end: Alignment.bottomCenter,
///             colors: <Color>[Colors.orange, Colors.red],
///             stops: <double>[0.0, 1.0],
///           ),
///         ),
///       ),
///     ),
///   );
/// }
/// ```
/// {@end-tool}
@immutable
class InteractiveViewer extends StatefulWidget {
  /// Create an InteractiveViewer.
  ///
77
  /// The `child` parameter must not be null.
78
  InteractiveViewer({
79
    Key? key,
80
    this.clipBehavior = Clip.hardEdge,
81
    this.alignPanAxis = false,
82 83 84 85 86 87 88 89 90 91 92 93
    this.boundaryMargin = EdgeInsets.zero,
    this.constrained = true,
    // These default scale values were eyeballed as reasonable limits for common
    // use cases.
    this.maxScale = 2.5,
    this.minScale = 0.8,
    this.onInteractionEnd,
    this.onInteractionStart,
    this.onInteractionUpdate,
    this.panEnabled = true,
    this.scaleEnabled = true,
    this.transformationController,
94
    required Widget child,
95 96
  }) : assert(alignPanAxis != null),
       assert(child != null),
97 98 99 100 101 102 103 104 105 106 107 108
       assert(constrained != null),
       assert(minScale != null),
       assert(minScale > 0),
       assert(minScale.isFinite),
       assert(maxScale != null),
       assert(maxScale > 0),
       assert(!maxScale.isNaN),
       assert(maxScale >= minScale),
       assert(panEnabled != null),
       assert(scaleEnabled != null),
       // boundaryMargin must be either fully infinite or fully finite, but not
       // a mix of both.
109 110
       assert(
         (boundaryMargin.horizontal.isInfinite
111 112
           && boundaryMargin.vertical.isInfinite) || (boundaryMargin.top.isFinite
           && boundaryMargin.right.isFinite && boundaryMargin.bottom.isFinite
113 114
           && boundaryMargin.left.isFinite),
       ),
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
       builder = _getBuilderForChild(child),
       super(key: key);

  /// Creates an InteractiveViewer for a child that is created on demand.
  ///
  /// Can be used to render a child that changes in response to the current
  /// transformation.
  ///
  /// The [builder] parameter must not be null. See its docs for an example of
  /// using it to optimize a large child.
  InteractiveViewer.builder({
    Key? key,
    this.clipBehavior = Clip.hardEdge,
    this.alignPanAxis = false,
    this.boundaryMargin = EdgeInsets.zero,
    // These default scale values were eyeballed as reasonable limits for common
    // use cases.
    this.maxScale = 2.5,
    this.minScale = 0.8,
    this.onInteractionEnd,
    this.onInteractionStart,
    this.onInteractionUpdate,
    this.panEnabled = true,
    this.scaleEnabled = true,
    this.transformationController,
    required this.builder,
  }) : assert(alignPanAxis != null),
       assert(builder != null),
       assert(minScale != null),
       assert(minScale > 0),
       assert(minScale.isFinite),
       assert(maxScale != null),
       assert(maxScale > 0),
       assert(!maxScale.isNaN),
       assert(maxScale >= minScale),
       assert(panEnabled != null),
       assert(scaleEnabled != null),
       // boundaryMargin must be either fully infinite or fully finite, but not
       // a mix of both.
       assert((boundaryMargin.horizontal.isInfinite
           && boundaryMargin.vertical.isInfinite) || (boundaryMargin.top.isFinite
           && boundaryMargin.right.isFinite && boundaryMargin.bottom.isFinite
           && boundaryMargin.left.isFinite)),
       constrained = false,
159 160
       super(key: key);

161 162 163 164 165 166 167
  /// If set to [Clip.none], the child may extend beyond the size of the InteractiveViewer,
  /// but it will not receive gestures in these areas.
  /// Be sure that the InteractiveViewer is the desired size when using [Clip.none].
  ///
  /// Defaults to [Clip.hardEdge].
  final Clip clipBehavior;

168 169 170 171 172 173 174
  /// If true, panning is only allowed in the direction of the horizontal axis
  /// or the vertical axis.
  ///
  /// In other words, when this is true, diagonal panning is not allowed. A
  /// single gesture begun along one axis cannot also cause panning along the
  /// other axis without stopping and beginning a new gesture. This is a common
  /// pattern in tables where data is displayed in columns and rows.
175 176 177 178
  ///
  /// See also:
  ///  * [constrained], which has an example of creating a table that uses
  ///    alignPanAxis.
179 180
  final bool alignPanAxis;

181 182 183 184 185 186 187 188 189 190 191 192 193
  /// A margin for the visible boundaries of the child.
  ///
  /// Any transformation that results in the viewport being able to view outside
  /// of the boundaries will be stopped at the boundary. The boundaries do not
  /// rotate with the rest of the scene, so they are always aligned with the
  /// viewport.
  ///
  /// To produce no boundaries at all, pass infinite [EdgeInsets], such as
  /// `EdgeInsets.all(double.infinity)`.
  ///
  /// No edge can be NaN.
  ///
  /// Defaults to [EdgeInsets.zero], which results in boundaries that are the
194
  /// exact same size and position as the child.
195 196
  final EdgeInsets boundaryMargin;

197 198 199 200 201 202 203 204
  /// Builds the child of this widget.
  ///
  /// If a child is passed directly, then this is simply a function that returns
  /// that child.
  ///
  /// If using the [InteractiveViewer.builder] constructor, this can be passed
  /// directly. This allows the child to be built in response to the current
  /// transformation.
205
  ///
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
  /// {@tool dartpad --template=freeform}
  ///
  /// This example shows how to use builder to create a [Table] whose cell
  /// contents are only built when they are visible. Built and remove cells are
  /// logged in the console for illustration.
  ///
  /// ```dart main
  /// import 'package:vector_math/vector_math_64.dart' show Quad, Vector3;
  ///
  /// import 'package:flutter/material.dart';
  /// import 'package:flutter/widgets.dart';
  ///
  /// void main() => runApp(const IVBuilderExampleApp());
  ///
  /// class IVBuilderExampleApp extends StatelessWidget {
  ///   const IVBuilderExampleApp({Key? key}) : super(key: key);
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return MaterialApp(
  ///       home: Scaffold(
  ///         appBar: AppBar(
  ///           title: const Text('IV Builder Example'),
  ///         ),
  ///         body: _IVBuilderExample(),
  ///       ),
  ///     );
  ///   }
  /// }
  ///
  /// class _IVBuilderExample extends StatefulWidget {
  ///   @override
  ///   _IVBuilderExampleState createState() => _IVBuilderExampleState();
  /// }
  ///
  /// class _IVBuilderExampleState extends State<_IVBuilderExample> {
  ///   final TransformationController _transformationController = TransformationController();
  ///
  ///   static const double _cellWidth = 200.0;
  ///   static const double _cellHeight = 26.0;
  ///
  ///   // Returns true iff the given cell is currently visible. Caches viewport
  ///   // calculations.
  ///   late Quad _cachedViewport;
  ///   late int _firstVisibleRow;
  ///   late int _firstVisibleColumn;
  ///   late int _lastVisibleRow;
  ///   late int _lastVisibleColumn;
  ///   bool _isCellVisible(int row, int column, Quad viewport) {
  ///     if (viewport != _cachedViewport) {
  ///       final Rect aabb = _axisAlignedBoundingBox(viewport);
  ///       _cachedViewport = viewport;
  ///       _firstVisibleRow = (aabb.top / _cellHeight).floor();
  ///       _firstVisibleColumn = (aabb.left / _cellWidth).floor();
  ///       _lastVisibleRow = (aabb.bottom / _cellHeight).floor();
  ///       _lastVisibleColumn = (aabb.right / _cellWidth).floor();
  ///     }
  ///     return row >= _firstVisibleRow && row <= _lastVisibleRow
  ///         && column >= _firstVisibleColumn && column <= _lastVisibleColumn;
  ///   }
  ///
  ///   // Returns the axis aligned bounding box for the given Quad, which might not
  ///   // be axis aligned.
  ///   Rect _axisAlignedBoundingBox(Quad quad) {
  ///     double? xMin;
  ///     double? xMax;
  ///     double? yMin;
  ///     double? yMax;
  ///     for (final Vector3 point in <Vector3>[quad.point0, quad.point1, quad.point2, quad.point3]) {
  ///       if (xMin == null || point.x < xMin) {
  ///         xMin = point.x;
  ///       }
  ///       if (xMax == null || point.x > xMax) {
  ///         xMax = point.x;
  ///       }
  ///       if (yMin == null || point.y < yMin) {
  ///         yMin = point.y;
  ///       }
  ///       if (yMax == null || point.y > yMax) {
  ///         yMax = point.y;
  ///       }
  ///     }
  ///     return Rect.fromLTRB(xMin!, yMin!, xMax!, yMax!);
  ///   }
  ///
  ///   void _onChangeTransformation() {
  ///     setState(() {});
  ///   }
  ///
  ///   @override
  ///   void initState() {
  ///     super.initState();
  ///     _transformationController.addListener(_onChangeTransformation);
  ///   }
  ///
  ///   @override
  ///   void dispose() {
  ///     _transformationController.removeListener(_onChangeTransformation);
  ///     super.dispose();
  ///   }
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return Center(
  ///       child: LayoutBuilder(
  ///         builder: (BuildContext context, BoxConstraints constraints) {
  ///           return InteractiveViewer.builder(
  ///             alignPanAxis: true,
  ///             scaleEnabled: false,
  ///             transformationController: _transformationController,
  ///             builder: (BuildContext context, Quad viewport) {
  ///               // A simple extension of Table that builds cells.
  ///               return _TableBuilder(
  ///                 rowCount: 60,
  ///                 columnCount: 6,
  ///                 cellWidth: _cellWidth,
  ///                 builder: (BuildContext context, int row, int column) {
  ///                   if (!_isCellVisible(row, column, viewport)) {
  ///                     print('removing cell ($row, $column)');
  ///                     return Container(height: _cellHeight);
  ///                   }
  ///                   print('building cell ($row, $column)');
  ///                   return Container(
  ///                     height: _cellHeight,
  ///                     color: row % 2 + column % 2 == 1 ? Colors.white : Colors.grey.withOpacity(0.1),
  ///                     child: Align(
  ///                       alignment: Alignment.centerLeft,
  ///                       child: Text('$row x $column'),
  ///                     ),
  ///                   );
  ///                 }
  ///               );
  ///             },
  ///           );
  ///         },
  ///       ),
  ///     );
  ///   }
  /// }
  ///
  /// typedef _CellBuilder = Widget Function(BuildContext context, int row, int column);
  ///
  /// class _TableBuilder extends StatelessWidget {
  ///   const _TableBuilder({
  ///     required this.rowCount,
  ///     required this.columnCount,
  ///     required this.cellWidth,
  ///     required this.builder,
  ///   }) : assert(rowCount > 0),
  ///        assert(columnCount > 0);
  ///
  ///   final int rowCount;
  ///   final int columnCount;
  ///   final double cellWidth;
  ///   final _CellBuilder builder;
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
  ///     return Table(
  ///       // ignore: prefer_const_literals_to_create_immutables
  ///       columnWidths: <int, TableColumnWidth>{
  ///         for (int column = 0; column < columnCount; column++)
  ///           column: FixedColumnWidth(cellWidth),
  ///       },
  ///       // ignore: prefer_const_literals_to_create_immutables
  ///       children: <TableRow>[
  ///         for (int row = 0; row < rowCount; row++)
  ///           // ignore: prefer_const_constructors
  ///           TableRow(
  ///             // ignore: prefer_const_literals_to_create_immutables
  ///             children: <Widget>[
  ///               for (int column = 0; column < columnCount; column++)
  ///                 builder(context, row, column),
  ///             ],
  ///           ),
  ///       ],
  ///     );
  ///   }
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// See also:
  ///
  ///   * [ListView.builder], which follows a similar pattern.
  ///   * [InteractiveViewer.builder], which has an example of building the
  ///     child on demand.
  final InteractiveViewerWidgetBuilder builder;
394 395 396 397 398 399 400

  /// Whether the normal size constraints at this point in the widget tree are
  /// applied to the child.
  ///
  /// If set to false, then the child will be given infinite constraints. This
  /// is often useful when a child should be bigger than the InteractiveViewer.
  ///
401 402 403 404 405 406 407 408 409
  /// For example, for a child which is bigger than the viewport but can be
  /// panned to reveal parts that were initially offscreen, [constrained] must
  /// be set to false to allow it to size itself properly. If [constrained] is
  /// true and the child can only size itself to the viewport, then areas
  /// initially outside of the viewport will not be able to receive user
  /// interaction events. If experiencing regions of the child that are not
  /// receptive to user gestures, make sure [constrained] is false and the child
  /// is sized properly.
  ///
410 411
  /// Defaults to true.
  ///
412
  /// {@tool dartpad --template=stateless_widget_scaffold}
413 414 415 416 417 418 419
  /// This example shows how to create a pannable table. Because the table is
  /// larger than the entire screen, setting `constrained` to false is necessary
  /// to allow it to be drawn to its full size. The parts of the table that
  /// exceed the screen size can then be panned into view.
  ///
  /// ```dart
  ///   Widget build(BuildContext context) {
420 421
  ///     const int _rowCount = 48;
  ///     const int _columnCount = 6;
422
  ///
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  ///     return InteractiveViewer(
  ///       alignPanAxis: true,
  ///       constrained: false,
  ///       scaleEnabled: false,
  ///       child: Table(
  ///         columnWidths: <int, TableColumnWidth>{
  ///           for (int column = 0; column < _columnCount; column += 1)
  ///             column: const FixedColumnWidth(200.0),
  ///         },
  ///         children: <TableRow>[
  ///           for (int row = 0; row < _rowCount; row += 1)
  ///             TableRow(
  ///               children: <Widget>[
  ///                 for (int column = 0; column < _columnCount; column += 1)
  ///                   Container(
  ///                     height: 26,
  ///                     color: row % 2 + column % 2 == 1
  ///                         ? Colors.white
  ///                         : Colors.grey.withOpacity(0.1),
  ///                     child: Align(
  ///                       alignment: Alignment.centerLeft,
  ///                       child: Text('$row x $column'),
445
  ///                     ),
446 447 448 449
  ///                   ),
  ///               ],
  ///             ),
  ///         ],
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
  ///       ),
  ///     );
  ///   }
  /// ```
  /// {@end-tool}
  final bool constrained;

  /// If false, the user will be prevented from panning.
  ///
  /// Defaults to true.
  ///
  /// See also:
  ///
  ///   * [scaleEnabled], which is similar but for scale.
  final bool panEnabled;

  /// If false, the user will be prevented from scaling.
  ///
  /// Defaults to true.
  ///
  /// See also:
  ///
  ///   * [panEnabled], which is similar but for panning.
  final bool scaleEnabled;

  /// The maximum allowed scale.
  ///
  /// The scale will be clamped between this and [minScale] inclusively.
  ///
  /// Defaults to 2.5.
  ///
  /// Cannot be null, and must be greater than zero and greater than minScale.
  final double maxScale;

  /// The minimum allowed scale.
  ///
  /// The scale will be clamped between this and [maxScale] inclusively.
  ///
488 489 490 491 492
  /// Scale is also affected by [boundaryMargin]. If the scale would result in
  /// viewing beyond the boundary, then it will not be allowed. By default,
  /// boundaryMargin is EdgeInsets.zero, so scaling below 1.0 will not be
  /// allowed in most cases without first increasing the boundaryMargin.
  ///
493 494 495 496 497 498 499 500
  /// Defaults to 0.8.
  ///
  /// Cannot be null, and must be a finite number greater than zero and less
  /// than maxScale.
  final double minScale;

  /// Called when the user ends a pan or scale gesture on the widget.
  ///
501
  /// At the time this is called, the [TransformationController] will have
502 503
  /// already been updated to reflect the change caused by the interaction,
  /// though a pan may cause an inertia animation after this is called as well.
504
  ///
505
  /// {@template flutter.widgets.InteractiveViewer.onInteractionEnd}
506 507
  /// Will be called even if the interaction is disabled with [panEnabled] or
  /// [scaleEnabled] for both touch gestures and mouse interactions.
508 509 510 511 512 513 514 515 516 517 518 519
  ///
  /// A [GestureDetector] wrapping the InteractiveViewer will not respond to
  /// [GestureDetector.onScaleStart], [GestureDetector.onScaleUpdate], and
  /// [GestureDetector.onScaleEnd]. Use [onInteractionStart],
  /// [onInteractionUpdate], and [onInteractionEnd] to respond to those
  /// gestures.
  /// {@endtemplate}
  ///
  /// See also:
  ///
  ///  * [onInteractionStart], which handles the start of the same interaction.
  ///  * [onInteractionUpdate], which handles an update to the same interaction.
520
  final GestureScaleEndCallback? onInteractionEnd;
521 522 523

  /// Called when the user begins a pan or scale gesture on the widget.
  ///
524 525 526
  /// At the time this is called, the [TransformationController] will not have
  /// changed due to this interaction.
  ///
527
  /// {@macro flutter.widgets.InteractiveViewer.onInteractionEnd}
528
  ///
529 530 531 532 533 534
  /// The coordinates provided in the details' `focalPoint` and
  /// `localFocalPoint` are normal Flutter event coordinates, not
  /// InteractiveViewer scene coordinates. See
  /// [TransformationController.toScene] for how to convert these coordinates to
  /// scene coordinates relative to the child.
  ///
535 536 537 538
  /// See also:
  ///
  ///  * [onInteractionUpdate], which handles an update to the same interaction.
  ///  * [onInteractionEnd], which handles the end of the same interaction.
539
  final GestureScaleStartCallback? onInteractionStart;
540 541 542

  /// Called when the user updates a pan or scale gesture on the widget.
  ///
543
  /// At the time this is called, the [TransformationController] will have
544 545
  /// already been updated to reflect the change caused by the interaction, if
  /// the interation caused the matrix to change.
546
  ///
547
  /// {@macro flutter.widgets.InteractiveViewer.onInteractionEnd}
548
  ///
549 550 551 552 553 554
  /// The coordinates provided in the details' `focalPoint` and
  /// `localFocalPoint` are normal Flutter event coordinates, not
  /// InteractiveViewer scene coordinates. See
  /// [TransformationController.toScene] for how to convert these coordinates to
  /// scene coordinates relative to the child.
  ///
555 556 557 558
  /// See also:
  ///
  ///  * [onInteractionStart], which handles the start of the same interaction.
  ///  * [onInteractionEnd], which handles the end of the same interaction.
559
  final GestureScaleUpdateCallback? onInteractionUpdate;
560 561 562 563 564 565 566 567

  /// A [TransformationController] for the transformation performed on the
  /// child.
  ///
  /// Whenever the child is transformed, the [Matrix4] value is updated and all
  /// listeners are notified. If the value is set, InteractiveViewer will update
  /// to respect the new value.
  ///
568
  /// {@tool dartpad --template=stateful_widget_material_ticker}
569 570 571 572 573
  /// This example shows how transformationController can be used to animate the
  /// transformation back to its starting position.
  ///
  /// ```dart
  /// final TransformationController _transformationController = TransformationController();
574 575
  /// Animation<Matrix4>? _animationReset;
  /// late final AnimationController _controllerReset;
576 577
  ///
  /// void _onAnimateReset() {
578
  ///   _transformationController.value = _animationReset!.value;
579
  ///   if (!_controllerReset.isAnimating) {
580
  ///     _animationReset!.removeListener(_onAnimateReset);
581 582 583 584 585 586 587 588 589 590 591
  ///     _animationReset = null;
  ///     _controllerReset.reset();
  ///   }
  /// }
  ///
  /// void _animateResetInitialize() {
  ///   _controllerReset.reset();
  ///   _animationReset = Matrix4Tween(
  ///     begin: _transformationController.value,
  ///     end: Matrix4.identity(),
  ///   ).animate(_controllerReset);
592
  ///   _animationReset!.addListener(_onAnimateReset);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
  ///   _controllerReset.forward();
  /// }
  ///
  /// // Stop a running reset to home transform animation.
  /// void _animateResetStop() {
  ///   _controllerReset.stop();
  ///   _animationReset?.removeListener(_onAnimateReset);
  ///   _animationReset = null;
  ///   _controllerReset.reset();
  /// }
  ///
  /// void _onInteractionStart(ScaleStartDetails details) {
  ///   // If the user tries to cause a transformation while the reset animation is
  ///   // running, cancel the reset animation.
  ///   if (_controllerReset.status == AnimationStatus.forward) {
  ///     _animateResetStop();
  ///   }
  /// }
  ///
  /// @override
  /// void initState() {
  ///   super.initState();
  ///   _controllerReset = AnimationController(
  ///     vsync: this,
  ///     duration: const Duration(milliseconds: 400),
  ///   );
  /// }
  ///
  /// @override
  /// void dispose() {
  ///   _controllerReset.dispose();
  ///   super.dispose();
  /// }
  ///
  /// @override
  /// Widget build(BuildContext context) {
  ///   return Scaffold(
  ///     backgroundColor: Theme.of(context).colorScheme.primary,
  ///     appBar: AppBar(
  ///       automaticallyImplyLeading: false,
  ///       title: const Text('Controller demo'),
  ///     ),
  ///     body: Center(
  ///       child: InteractiveViewer(
637
  ///         boundaryMargin: const EdgeInsets.all(double.infinity),
638 639 640 641 642
  ///         transformationController: _transformationController,
  ///         minScale: 0.1,
  ///         maxScale: 1.0,
  ///         onInteractionStart: _onInteractionStart,
  ///         child: Container(
643
  ///           decoration: const BoxDecoration(
644 645 646 647 648 649 650 651 652 653
  ///             gradient: LinearGradient(
  ///               begin: Alignment.topCenter,
  ///               end: Alignment.bottomCenter,
  ///               colors: <Color>[Colors.orange, Colors.red],
  ///               stops: <double>[0.0, 1.0],
  ///             ),
  ///           ),
  ///         ),
  ///       ),
  ///     ),
654
  ///     persistentFooterButtons: <Widget>[
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
  ///       IconButton(
  ///         onPressed: _animateResetInitialize,
  ///         tooltip: 'Reset',
  ///         color: Theme.of(context).colorScheme.surface,
  ///         icon: const Icon(Icons.replay),
  ///       ),
  ///     ],
  ///   );
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// See also:
  ///
  ///  * [ValueNotifier], the parent class of TransformationController.
  ///  * [TextEditingController] for an example of another similar pattern.
671
  final TransformationController? transformationController;
672

673 674 675 676 677 678 679
  // Get a InteractiveViewerWidgetBuilder that simply returns the given child.
  static InteractiveViewerWidgetBuilder _getBuilderForChild(Widget child) {
    return (BuildContext context, Quad viewport) {
      return child;
    };
  }

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
  /// Returns the closest point to the given point on the given line segment.
  @visibleForTesting
  static Vector3 getNearestPointOnLine(Vector3 point, Vector3 l1, Vector3 l2) {
    final double lengthSquared = math.pow(l2.x - l1.x, 2.0).toDouble()
        + math.pow(l2.y - l1.y, 2.0).toDouble();

    // In this case, l1 == l2.
    if (lengthSquared == 0) {
      return l1;
    }

    // Calculate how far down the line segment the closest point is and return
    // the point.
    final Vector3 l1P = point - l1;
    final Vector3 l1L2 = l2 - l1;
    final double fraction = (l1P.dot(l1L2) / lengthSquared).clamp(0.0, 1.0).toDouble();
    return l1 + l1L2 * fraction;
  }

  /// Given a quad, return its axis aligned bounding box.
  @visibleForTesting
  static Quad getAxisAlignedBoundingBox(Quad quad) {
    final double minX = math.min(
      quad.point0.x,
      math.min(
        quad.point1.x,
        math.min(
          quad.point2.x,
          quad.point3.x,
        ),
      ),
    );
    final double minY = math.min(
      quad.point0.y,
      math.min(
        quad.point1.y,
        math.min(
          quad.point2.y,
          quad.point3.y,
        ),
      ),
    );
    final double maxX = math.max(
      quad.point0.x,
      math.max(
        quad.point1.x,
        math.max(
          quad.point2.x,
          quad.point3.x,
        ),
      ),
    );
    final double maxY = math.max(
      quad.point0.y,
      math.max(
        quad.point1.y,
        math.max(
          quad.point2.y,
          quad.point3.y,
        ),
      ),
    );
    return Quad.points(
      Vector3(minX, minY, 0),
      Vector3(maxX, minY, 0),
      Vector3(maxX, maxY, 0),
      Vector3(minX, maxY, 0),
    );
  }

  /// Returns true iff the point is inside the rectangle given by the Quad,
  /// inclusively.
  /// Algorithm from https://math.stackexchange.com/a/190373.
  @visibleForTesting
  static bool pointIsInside(Vector3 point, Quad quad) {
    final Vector3 aM = point - quad.point0;
    final Vector3 aB = quad.point1 - quad.point0;
    final Vector3 aD = quad.point3 - quad.point0;

    final double aMAB = aM.dot(aB);
    final double aBAB = aB.dot(aB);
    final double aMAD = aM.dot(aD);
    final double aDAD = aD.dot(aD);

    return 0 <= aMAB && aMAB <= aBAB && 0 <= aMAD && aMAD <= aDAD;
  }

  /// Get the point inside (inclusively) the given Quad that is nearest to the
  /// given Vector3.
  @visibleForTesting
  static Vector3 getNearestPointInside(Vector3 point, Quad quad) {
    // If the point is inside the axis aligned bounding box, then it's ok where
    // it is.
    if (pointIsInside(point, quad)) {
      return point;
    }

    // Otherwise, return the nearest point on the quad.
    final List<Vector3> closestPoints = <Vector3>[
      InteractiveViewer.getNearestPointOnLine(point, quad.point0, quad.point1),
      InteractiveViewer.getNearestPointOnLine(point, quad.point1, quad.point2),
      InteractiveViewer.getNearestPointOnLine(point, quad.point2, quad.point3),
      InteractiveViewer.getNearestPointOnLine(point, quad.point3, quad.point0),
    ];
    double minDistance = double.infinity;
785
    late Vector3 closestOverall;
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    for (final Vector3 closePoint in closestPoints) {
      final double distance = math.sqrt(
        math.pow(point.x - closePoint.x, 2) + math.pow(point.y - closePoint.y, 2),
      );
      if (distance < minDistance) {
        minDistance = distance;
        closestOverall = closePoint;
      }
    }
    return closestOverall;
  }

  @override _InteractiveViewerState createState() => _InteractiveViewerState();
}

class _InteractiveViewerState extends State<InteractiveViewer> with TickerProviderStateMixin {
802
  TransformationController? _transformationController;
803 804 805

  final GlobalKey _childKey = GlobalKey();
  final GlobalKey _parentKey = GlobalKey();
806 807 808 809 810 811
  Animation<Offset>? _animation;
  late AnimationController _controller;
  Axis? _panAxis; // Used with alignPanAxis.
  Offset? _referenceFocalPoint; // Point where the current gesture began.
  double? _scaleStart; // Scale value at start of scaling gesture.
  double? _rotationStart = 0.0; // Rotation at start of rotation gesture.
812
  double _currentRotation = 0.0; // Rotation of _transformationController.value.
813
  _GestureType? _gestureType;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

  // TODO(justinmc): Add rotateEnabled parameter to the widget and remove this
  // hardcoded value when the rotation feature is implemented.
  // https://github.com/flutter/flutter/issues/57698
  final bool _rotateEnabled = false;

  // Used as the coefficient of friction in the inertial translation animation.
  // This value was eyeballed to give a feel similar to Google Photos.
  static const double _kDrag = 0.0000135;

  // The _boundaryRect is calculated by adding the boundaryMargin to the size of
  // the child.
  Rect get _boundaryRect {
    assert(_childKey.currentContext != null);
    assert(!widget.boundaryMargin.left.isNaN);
    assert(!widget.boundaryMargin.right.isNaN);
    assert(!widget.boundaryMargin.top.isNaN);
    assert(!widget.boundaryMargin.bottom.isNaN);

833
    final RenderBox childRenderBox = _childKey.currentContext!.findRenderObject()! as RenderBox;
834
    final Size childSize = childRenderBox.size;
835
    final Rect boundaryRect = widget.boundaryMargin.inflateRect(Offset.zero & childSize);
836 837
    // Boundaries that are partially infinite are not allowed because Matrix4's
    // rotation and translation methods don't handle infinites well.
838 839
    assert(
      boundaryRect.isFinite ||
840 841 842
        (boundaryRect.left.isInfinite
        && boundaryRect.top.isInfinite
        && boundaryRect.right.isInfinite
843 844 845
        && boundaryRect.bottom.isInfinite),
      'boundaryRect must either be infinite in all directions or finite in all directions.',
    );
846
    return boundaryRect;
847 848 849 850 851
  }

  // The Rect representing the child's parent.
  Rect get _viewport {
    assert(_parentKey.currentContext != null);
852
    final RenderBox parentRenderBox = _parentKey.currentContext!.findRenderObject()! as RenderBox;
853 854 855 856 857 858 859 860 861 862
    return Offset.zero & parentRenderBox.size;
  }

  // Return a new matrix representing the given matrix after applying the given
  // translation.
  Matrix4 _matrixTranslate(Matrix4 matrix, Offset translation) {
    if (translation == Offset.zero) {
      return matrix.clone();
    }

863
    final Offset alignedTranslation = widget.alignPanAxis && _panAxis != null
864
      ? _alignAxis(translation, _panAxis!)
865 866
      : translation;

867
    final Matrix4 nextMatrix = matrix.clone()..translate(
868 869
      alignedTranslation.dx,
      alignedTranslation.dy,
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    );

    // Transform the viewport to determine where its four corners will be after
    // the child has been transformed.
    final Quad nextViewport = _transformViewport(nextMatrix, _viewport);

    // If the boundaries are infinite, then no need to check if the translation
    // fits within them.
    if (_boundaryRect.isInfinite) {
      return nextMatrix;
    }

    // Expand the boundaries with rotation. This prevents the problem where a
    // mismatch in orientation between the viewport and boundaries effectively
    // limits translation. With this approach, all points that are visible with
    // no rotation are visible after rotation.
    final Quad boundariesAabbQuad = _getAxisAlignedBoundingBoxWithRotation(
      _boundaryRect,
      _currentRotation,
    );

    // If the given translation fits completely within the boundaries, allow it.
    final Offset offendingDistance = _exceedsBy(boundariesAabbQuad, nextViewport);
    if (offendingDistance == Offset.zero) {
      return nextMatrix;
    }

    // Desired translation goes out of bounds, so translate to the nearest
    // in-bounds point instead.
    final Offset nextTotalTranslation = _getMatrixTranslation(nextMatrix);
    final double currentScale = matrix.getMaxScaleOnAxis();
    final Offset correctedTotalTranslation = Offset(
      nextTotalTranslation.dx - offendingDistance.dx * currentScale,
      nextTotalTranslation.dy - offendingDistance.dy * currentScale,
    );
    // TODO(justinmc): This needs some work to handle rotation properly. The
    // idea is that the boundaries are axis aligned (boundariesAabbQuad), but
    // calculating the translation to put the viewport inside that Quad is more
    // complicated than this when rotated.
     // https://github.com/flutter/flutter/issues/57698
    final Matrix4 correctedMatrix = matrix.clone()..setTranslation(Vector3(
      correctedTotalTranslation.dx,
      correctedTotalTranslation.dy,
      0.0,
    ));

    // Double check that the corrected translation fits.
    final Quad correctedViewport = _transformViewport(correctedMatrix, _viewport);
    final Offset offendingCorrectedDistance = _exceedsBy(boundariesAabbQuad, correctedViewport);
    if (offendingCorrectedDistance == Offset.zero) {
      return correctedMatrix;
    }

    // If the corrected translation doesn't fit in either direction, don't allow
    // any translation at all. This happens when the viewport is larger than the
    // entire boundary.
    if (offendingCorrectedDistance.dx != 0.0 && offendingCorrectedDistance.dy != 0.0) {
      return matrix.clone();
    }

    // Otherwise, allow translation in only the direction that fits. This
    // happens when the viewport is larger than the boundary in one direction.
    final Offset unidirectionalCorrectedTotalTranslation = Offset(
      offendingCorrectedDistance.dx == 0.0 ? correctedTotalTranslation.dx : 0.0,
      offendingCorrectedDistance.dy == 0.0 ? correctedTotalTranslation.dy : 0.0,
    );
    return matrix.clone()..setTranslation(Vector3(
      unidirectionalCorrectedTotalTranslation.dx,
      unidirectionalCorrectedTotalTranslation.dy,
      0.0,
    ));
  }

  // Return a new matrix representing the given matrix after applying the given
  // scale.
  Matrix4 _matrixScale(Matrix4 matrix, double scale) {
    if (scale == 1.0) {
      return matrix.clone();
    }
    assert(scale != 0.0);

    // Don't allow a scale that results in an overall scale beyond min/max
    // scale.
953
    final double currentScale = _transformationController!.value.getMaxScaleOnAxis();
954 955 956 957 958 959 960 961 962
    final double totalScale = math.max(
      currentScale * scale,
      // Ensure that the scale cannot make the child so big that it can't fit
      // inside the boundaries (in either direction).
      math.max(
        _viewport.width / _boundaryRect.width,
        _viewport.height / _boundaryRect.height,
      ),
    );
963 964 965
    final double clampedTotalScale = totalScale.clamp(
      widget.minScale,
      widget.maxScale,
966
    );
967
    final double clampedScale = clampedTotalScale / currentScale;
968
    return matrix.clone()..scale(clampedScale);
969 970 971 972 973 974 975 976
  }

  // Return a new matrix representing the given matrix after applying the given
  // rotation.
  Matrix4 _matrixRotate(Matrix4 matrix, double rotation, Offset focalPoint) {
    if (rotation == 0) {
      return matrix.clone();
    }
977
    final Offset focalPointScene = _transformationController!.toScene(
978 979 980 981 982 983 984 985 986 987
      focalPoint,
    );
    return matrix
      .clone()
      ..translate(focalPointScene.dx, focalPointScene.dy)
      ..rotateZ(-rotation)
      ..translate(-focalPointScene.dx, -focalPointScene.dy);
  }

  // Returns true iff the given _GestureType is enabled.
988
  bool _gestureIsSupported(_GestureType? gestureType) {
989 990 991 992 993 994 995 996
    switch (gestureType) {
      case _GestureType.rotate:
        return _rotateEnabled;

      case _GestureType.scale:
        return widget.scaleEnabled;

      case _GestureType.pan:
997
      case null:
998
        return widget.panEnabled;
999 1000 1001
    }
  }

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
  // Decide which type of gesture this is by comparing the amount of scale
  // and rotation in the gesture, if any. Scale starts at 1 and rotation
  // starts at 0. Pan will have no scale and no rotation because it uses only one
  // finger.
  _GestureType _getGestureType(ScaleUpdateDetails details) {
    final double scale = !widget.scaleEnabled ? 1.0 : details.scale;
    final double rotation = !_rotateEnabled ? 0.0 : details.rotation;
    if ((scale - 1).abs() > rotation.abs()) {
      return _GestureType.scale;
    } else if (rotation != 0.0) {
      return _GestureType.rotate;
    } else {
      return _GestureType.pan;
    }
  }

1018 1019 1020
  // Handle the start of a gesture. All of pan, scale, and rotate are handled
  // with GestureDetector's scale gesture.
  void _onScaleStart(ScaleStartDetails details) {
1021
    widget.onInteractionStart?.call(details);
1022 1023 1024 1025 1026 1027 1028 1029 1030

    if (_controller.isAnimating) {
      _controller.stop();
      _controller.reset();
      _animation?.removeListener(_onAnimate);
      _animation = null;
    }

    _gestureType = null;
1031
    _panAxis = null;
1032 1033
    _scaleStart = _transformationController!.value.getMaxScaleOnAxis();
    _referenceFocalPoint = _transformationController!.toScene(
1034 1035 1036 1037 1038 1039 1040 1041
      details.localFocalPoint,
    );
    _rotationStart = _currentRotation;
  }

  // Handle an update to an ongoing gesture. All of pan, scale, and rotate are
  // handled with GestureDetector's scale gesture.
  void _onScaleUpdate(ScaleUpdateDetails details) {
1042 1043
    final double scale = _transformationController!.value.getMaxScaleOnAxis();
    final Offset focalPointScene = _transformationController!.toScene(
1044 1045
      details.localFocalPoint,
    );
1046

1047
    if (_gestureType == _GestureType.pan) {
1048 1049 1050 1051 1052 1053 1054
      // When a gesture first starts, it sometimes has no change in scale and
      // rotation despite being a two-finger gesture. Here the gesture is
      // allowed to be reinterpreted as its correct type after originally
      // being marked as a pan.
      _gestureType = _getGestureType(details);
    } else {
      _gestureType ??= _getGestureType(details);
1055
    }
1056
    if (!_gestureIsSupported(_gestureType)) {
1057
      widget.onInteractionUpdate?.call(details);
1058 1059 1060
      return;
    }

1061
    switch (_gestureType!) {
1062
      case _GestureType.scale:
1063
        assert(_scaleStart != null);
1064 1065 1066
        // details.scale gives us the amount to change the scale as of the
        // start of this gesture, so calculate the amount to scale as of the
        // previous call to _onScaleUpdate.
1067
        final double desiredScale = _scaleStart! * details.scale;
1068
        final double scaleChange = desiredScale / scale;
1069 1070
        _transformationController!.value = _matrixScale(
          _transformationController!.value,
1071 1072 1073 1074 1075 1076 1077
          scaleChange,
        );

        // While scaling, translate such that the user's two fingers stay on
        // the same places in the scene. That means that the focal point of
        // the scale should be on the same place in the scene before and after
        // the scale.
1078
        final Offset focalPointSceneScaled = _transformationController!.toScene(
1079 1080
          details.localFocalPoint,
        );
1081 1082 1083
        _transformationController!.value = _matrixTranslate(
          _transformationController!.value,
          focalPointSceneScaled - _referenceFocalPoint!,
1084 1085 1086 1087 1088 1089 1090
        );

        // details.localFocalPoint should now be at the same location as the
        // original _referenceFocalPoint point. If it's not, that's because
        // the translate came in contact with a boundary. In that case, update
        // _referenceFocalPoint so subsequent updates happen in relation to
        // the new effective focal point.
1091
        final Offset focalPointSceneCheck = _transformationController!.toScene(
1092 1093
          details.localFocalPoint,
        );
1094
        if (_round(_referenceFocalPoint!) != _round(focalPointSceneCheck)) {
1095 1096
          _referenceFocalPoint = focalPointSceneCheck;
        }
1097
        break;
1098 1099 1100

      case _GestureType.rotate:
        if (details.rotation == 0.0) {
1101
          widget.onInteractionUpdate?.call(details);
1102 1103
          return;
        }
1104 1105 1106
        final double desiredRotation = _rotationStart! + details.rotation;
        _transformationController!.value = _matrixRotate(
          _transformationController!.value,
1107 1108 1109 1110
          _currentRotation - desiredRotation,
          details.localFocalPoint,
        );
        _currentRotation = desiredRotation;
1111
        break;
1112 1113

      case _GestureType.pan:
1114 1115 1116 1117 1118
        assert(_referenceFocalPoint != null);
        // details may have a change in scale here when scaleEnabled is false.
        // In an effort to keep the behavior similar whether or not scaleEnabled
        // is true, these gestures are thrown away.
        if (details.scale != 1.0) {
1119
          widget.onInteractionUpdate?.call(details);
1120 1121
          return;
        }
1122
        _panAxis ??= _getPanAxis(_referenceFocalPoint!, focalPointScene);
1123 1124
        // Translate so that the same point in the scene is underneath the
        // focal point before and after the movement.
1125 1126 1127
        final Offset translationChange = focalPointScene - _referenceFocalPoint!;
        _transformationController!.value = _matrixTranslate(
          _transformationController!.value,
1128 1129
          translationChange,
        );
1130
        _referenceFocalPoint = _transformationController!.toScene(
1131 1132
          details.localFocalPoint,
        );
1133
        break;
1134
    }
1135
    widget.onInteractionUpdate?.call(details);
1136 1137 1138 1139 1140
  }

  // Handle the end of a gesture of _GestureType. All of pan, scale, and rotate
  // are handled with GestureDetector's scale gesture.
  void _onScaleEnd(ScaleEndDetails details) {
1141
    widget.onInteractionEnd?.call(details);
1142 1143 1144 1145 1146 1147 1148 1149
    _scaleStart = null;
    _rotationStart = null;
    _referenceFocalPoint = null;

    _animation?.removeListener(_onAnimate);
    _controller.reset();

    if (!_gestureIsSupported(_gestureType)) {
1150
      _panAxis = null;
1151 1152 1153 1154 1155
      return;
    }

    // If the scale ended with enough velocity, animate inertial movement.
    if (_gestureType != _GestureType.pan || details.velocity.pixelsPerSecond.distance < kMinFlingVelocity) {
1156
      _panAxis = null;
1157 1158 1159
      return;
    }

1160
    final Vector3 translationVector = _transformationController!.value.getTranslation();
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    final Offset translation = Offset(translationVector.x, translationVector.y);
    final FrictionSimulation frictionSimulationX = FrictionSimulation(
      _kDrag,
      translation.dx,
      details.velocity.pixelsPerSecond.dx,
    );
    final FrictionSimulation frictionSimulationY = FrictionSimulation(
      _kDrag,
      translation.dy,
      details.velocity.pixelsPerSecond.dy,
    );
    final double tFinal = _getFinalTime(
      details.velocity.pixelsPerSecond.distance,
      _kDrag,
    );
    _animation = Tween<Offset>(
      begin: translation,
      end: Offset(frictionSimulationX.finalX, frictionSimulationY.finalX),
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.decelerate,
    ));
    _controller.duration = Duration(milliseconds: (tFinal * 1000).round());
1184
    _animation!.addListener(_onAnimate);
1185 1186 1187 1188 1189 1190
    _controller.forward();
  }

  // Handle mousewheel scroll events.
  void _receivedPointerSignal(PointerSignalEvent event) {
    if (event is PointerScrollEvent) {
1191 1192 1193 1194
      // Ignore left and right scroll.
      if (event.scrollDelta.dy == 0.0) {
        return;
      }
1195 1196 1197 1198 1199 1200
      widget.onInteractionStart?.call(
        ScaleStartDetails(
          focalPoint: event.position,
          localFocalPoint: event.localPosition,
        ),
      );
1201 1202 1203 1204 1205 1206 1207

      // In the Flutter engine, the mousewheel scrollDelta is hardcoded to 20
      // per scroll, while a trackpad scroll can be any amount. The calculation
      // for scaleChange here was arbitrarily chosen to feel natural for both
      // trackpads and mousewheels on all platforms.
      final double scaleChange = math.exp(-event.scrollDelta.dy / 200);

1208
      if (!_gestureIsSupported(_GestureType.scale)) {
1209 1210 1211 1212 1213 1214 1215 1216
        widget.onInteractionUpdate?.call(ScaleUpdateDetails(
          focalPoint: event.position,
          localFocalPoint: event.localPosition,
          rotation: 0.0,
          scale: scaleChange,
          horizontalScale: 1.0,
          verticalScale: 1.0,
        ));
1217 1218 1219
        widget.onInteractionEnd?.call(ScaleEndDetails());
        return;
      }
1220

1221
      final Offset focalPointScene = _transformationController!.toScene(
1222 1223
        event.localPosition,
      );
1224

1225 1226
      _transformationController!.value = _matrixScale(
        _transformationController!.value,
1227 1228 1229 1230 1231
        scaleChange,
      );

      // After scaling, translate such that the event's position is at the
      // same scene point before and after the scale.
1232
      final Offset focalPointSceneScaled = _transformationController!.toScene(
1233 1234
        event.localPosition,
      );
1235 1236
      _transformationController!.value = _matrixTranslate(
        _transformationController!.value,
1237 1238
        focalPointSceneScaled - focalPointScene,
      );
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

      widget.onInteractionUpdate?.call(ScaleUpdateDetails(
        focalPoint: event.position,
        localFocalPoint: event.localPosition,
        rotation: 0.0,
        scale: scaleChange,
        horizontalScale: 1.0,
        verticalScale: 1.0,
      ));
      widget.onInteractionEnd?.call(ScaleEndDetails());
1249 1250 1251 1252 1253 1254
    }
  }

  // Handle inertia drag animation.
  void _onAnimate() {
    if (!_controller.isAnimating) {
1255
      _panAxis = null;
1256 1257 1258 1259 1260 1261
      _animation?.removeListener(_onAnimate);
      _animation = null;
      _controller.reset();
      return;
    }
    // Translate such that the resulting translation is _animation.value.
1262
    final Vector3 translationVector = _transformationController!.value.getTranslation();
1263
    final Offset translation = Offset(translationVector.x, translationVector.y);
1264
    final Offset translationScene = _transformationController!.toScene(
1265 1266
      translation,
    );
1267 1268
    final Offset animationScene = _transformationController!.toScene(
      _animation!.value,
1269 1270
    );
    final Offset translationChangeScene = animationScene - translationScene;
1271 1272
    _transformationController!.value = _matrixTranslate(
      _transformationController!.value,
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
      translationChangeScene,
    );
  }

  void _onTransformationControllerChange() {
    // A change to the TransformationController's value is a change to the
    // state.
    setState(() {});
  }

  @override
  void initState() {
    super.initState();

    _transformationController = widget.transformationController
        ?? TransformationController();
1289
    _transformationController!.addListener(_onTransformationControllerChange);
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    _controller = AnimationController(
      vsync: this,
    );
  }

  @override
  void didUpdateWidget(InteractiveViewer oldWidget) {
    super.didUpdateWidget(oldWidget);
    // Handle all cases of needing to dispose and initialize
    // transformationControllers.
    if (oldWidget.transformationController == null) {
      if (widget.transformationController != null) {
1302 1303
        _transformationController!.removeListener(_onTransformationControllerChange);
        _transformationController!.dispose();
1304
        _transformationController = widget.transformationController;
1305
        _transformationController!.addListener(_onTransformationControllerChange);
1306 1307 1308
      }
    } else {
      if (widget.transformationController == null) {
1309
        _transformationController!.removeListener(_onTransformationControllerChange);
1310
        _transformationController = TransformationController();
1311
        _transformationController!.addListener(_onTransformationControllerChange);
1312
      } else if (widget.transformationController != oldWidget.transformationController) {
1313
        _transformationController!.removeListener(_onTransformationControllerChange);
1314
        _transformationController = widget.transformationController;
1315
        _transformationController!.addListener(_onTransformationControllerChange);
1316 1317 1318 1319 1320 1321 1322
      }
    }
  }

  @override
  void dispose() {
    _controller.dispose();
1323
    _transformationController!.removeListener(_onTransformationControllerChange);
1324
    if (widget.transformationController == null) {
1325
      _transformationController!.dispose();
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // A GestureDetector allows the detection of panning and zooming gestures on
    // the child.
    return Listener(
      key: _parentKey,
      onPointerSignal: _receivedPointerSignal,
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          final Matrix4 matrix = _transformationController!.value;
          // When constrained is false, such as when using
          // InteractiveViewer.builder, then the viewport is the size of the
          // constraints.
          Widget child = Transform(
            transform: matrix,
            child: KeyedSubtree(
              key: _childKey,
              child: widget.builder(context, _transformViewport(matrix, Offset.zero & constraints.biggest)),
            ),
          );

          if (!widget.constrained) {
            child = OverflowBox(
              alignment: Alignment.topLeft,
              minWidth: 0.0,
              minHeight: 0.0,
              maxWidth: double.infinity,
              maxHeight: double.infinity,
              child: child,
            );
          }

          if (widget.clipBehavior != Clip.none) {
            child = ClipRect(
              clipBehavior: widget.clipBehavior,
              child: child,
            );
          }

          return GestureDetector(
            behavior: HitTestBehavior.opaque, // Necessary when panning off screen.
            dragStartBehavior: DragStartBehavior.start,
            onScaleEnd: _onScaleEnd,
            onScaleStart: _onScaleStart,
            onScaleUpdate: _onScaleUpdate,
            child: child,
          );
        },
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
      ),
    );
  }
}

/// A thin wrapper on [ValueNotifier] whose value is a [Matrix4] representing a
/// transformation.
///
/// The [value] defaults to the identity matrix, which corresponds to no
/// transformation.
///
/// See also:
///
///  * [InteractiveViewer.transformationController] for detailed documentation
///    on how to use TransformationController with [InteractiveViewer].
class TransformationController extends ValueNotifier<Matrix4> {
  /// Create an instance of [TransformationController].
  ///
  /// The [value] defaults to the identity matrix, which corresponds to no
  /// transformation.
1398
  TransformationController([Matrix4? value]) : super(value ?? Matrix4.identity());
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

  /// Return the scene point at the given viewport point.
  ///
  /// A viewport point is relative to the parent while a scene point is relative
  /// to the child, regardless of transformation. Calling toScene with a
  /// viewport point essentially returns the scene coordinate that lies
  /// underneath the viewport point given the transform.
  ///
  /// The viewport transforms as the inverse of the child (i.e. moving the child
  /// left is equivalent to moving the viewport right).
  ///
  /// This method is often useful when determining where an event on the parent
  /// occurs on the child. This example shows how to determine where a tap on
  /// the parent occurred on the child.
  ///
  /// ```dart
  /// @override
  /// void build(BuildContext context) {
  ///   return GestureDetector(
  ///     onTapUp: (TapUpDetails details) {
  ///       _childWasTappedAt = _transformationController.toScene(
  ///         details.localPosition,
  ///       );
  ///     },
  ///     child: InteractiveViewer(
  ///       transformationController: _transformationController,
  ///       child: child,
  ///     ),
  ///   );
  /// }
  /// ```
  Offset toScene(Offset viewportPoint) {
    // On viewportPoint, perform the inverse transformation of the scene to get
    // where the point would be in the scene before the transformation.
    final Matrix4 inverseMatrix = Matrix4.inverted(value);
    final Vector3 untransformed = inverseMatrix.transform3(Vector3(
      viewportPoint.dx,
      viewportPoint.dy,
      0,
    ));
    return Offset(untransformed.x, untransformed.y);
  }
}

// A classification of relevant user gestures. Each contiguous user gesture is
// represented by exactly one _GestureType.
enum _GestureType {
  pan,
  scale,
  rotate,
}

// Given a velocity and drag, calculate the time at which motion will come to
// a stop, within the margin of effectivelyMotionless.
double _getFinalTime(double velocity, double drag) {
  const double effectivelyMotionless = 10.0;
  return math.log(effectivelyMotionless / velocity) / math.log(drag / 100);
}

// Return the translation from the given Matrix4 as an Offset.
Offset _getMatrixTranslation(Matrix4 matrix) {
  final Vector3 nextTranslation = matrix.getTranslation();
  return Offset(nextTranslation.x, nextTranslation.y);
}

// Transform the four corners of the viewport by the inverse of the given
// matrix. This gives the viewport after the child has been transformed by the
// given matrix. The viewport transforms as the inverse of the child (i.e.
// moving the child left is equivalent to moving the viewport right).
Quad _transformViewport(Matrix4 matrix, Rect viewport) {
  final Matrix4 inverseMatrix = matrix.clone()..invert();
  return Quad.points(
    inverseMatrix.transform3(Vector3(
      viewport.topLeft.dx,
      viewport.topLeft.dy,
      0.0,
    )),
    inverseMatrix.transform3(Vector3(
      viewport.topRight.dx,
      viewport.topRight.dy,
      0.0,
    )),
    inverseMatrix.transform3(Vector3(
      viewport.bottomRight.dx,
      viewport.bottomRight.dy,
      0.0,
    )),
    inverseMatrix.transform3(Vector3(
      viewport.bottomLeft.dx,
      viewport.bottomLeft.dy,
      0.0,
    )),
  );
}

// Find the axis aligned bounding box for the rect rotated about its center by
// the given amount.
Quad _getAxisAlignedBoundingBoxWithRotation(Rect rect, double rotation) {
  final Matrix4 rotationMatrix = Matrix4.identity()
      ..translate(rect.size.width / 2, rect.size.height / 2)
      ..rotateZ(rotation)
      ..translate(-rect.size.width / 2, -rect.size.height / 2);
  final Quad boundariesRotated = Quad.points(
    rotationMatrix.transform3(Vector3(rect.left, rect.top, 0.0)),
    rotationMatrix.transform3(Vector3(rect.right, rect.top, 0.0)),
    rotationMatrix.transform3(Vector3(rect.right, rect.bottom, 0.0)),
    rotationMatrix.transform3(Vector3(rect.left, rect.bottom, 0.0)),
  );
  return InteractiveViewer.getAxisAlignedBoundingBox(boundariesRotated);
}

// Return the amount that viewport lies outside of boundary. If the viewport
// is completely contained within the boundary (inclusively), then returns
// Offset.zero.
Offset _exceedsBy(Quad boundary, Quad viewport) {
  final List<Vector3> viewportPoints = <Vector3>[
    viewport.point0, viewport.point1, viewport.point2, viewport.point3,
  ];
  Offset largestExcess = Offset.zero;
  for (final Vector3 point in viewportPoints) {
    final Vector3 pointInside = InteractiveViewer.getNearestPointInside(point, boundary);
    final Offset excess = Offset(
      pointInside.x - point.x,
      pointInside.y - point.y,
    );
    if (excess.dx.abs() > largestExcess.dx.abs()) {
      largestExcess = Offset(excess.dx, largestExcess.dy);
    }
    if (excess.dy.abs() > largestExcess.dy.abs()) {
      largestExcess = Offset(largestExcess.dx, excess.dy);
    }
  }

  return _round(largestExcess);
}

// Round the output values. This works around a precision problem where
// values that should have been zero were given as within 10^-10 of zero.
Offset _round(Offset offset) {
  return Offset(
    double.parse(offset.dx.toStringAsFixed(9)),
    double.parse(offset.dy.toStringAsFixed(9)),
  );
}
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556

// Align the given offset to the given axis by allowing movement only in the
// axis direction.
Offset _alignAxis(Offset offset, Axis axis) {
  switch (axis) {
    case Axis.horizontal:
      return Offset(offset.dx, 0.0);
    case Axis.vertical:
      return Offset(0.0, offset.dy);
  }
}

// Given two points, return the axis where the distance between the points is
// greatest. If they are equal, return null.
1557
Axis? _getPanAxis(Offset point1, Offset point2) {
1558 1559 1560 1561 1562 1563 1564
  if (point1 == point2) {
    return null;
  }
  final double x = point2.dx - point1.dx;
  final double y = point2.dy - point1.dy;
  return x.abs() > y.abs() ? Axis.horizontal : Axis.vertical;
}