semantics_debugger.dart 12.3 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5 6 7
// Copyright 2015 The Chromium 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/rendering.dart';
8
import 'package:sky_services/semantics/semantics.mojom.dart' as mojom;
Hixie's avatar
Hixie committed
9 10 11 12 13

import 'basic.dart';
import 'framework.dart';
import 'gesture_detector.dart';

14 15 16 17
/// Visualizes the semantics for the child.
///
/// This widget is useful for understand how an app presents itself to
/// accessibility technology.
Hixie's avatar
Hixie committed
18 19
class SemanticsDebugger extends StatefulComponent {
  const SemanticsDebugger({ Key key, this.child }) : super(key: key);
20

Hixie's avatar
Hixie committed
21
  final Widget child;
22

Hixie's avatar
Hixie committed
23 24 25 26 27 28
  _SemanticsDebuggerState createState() => new _SemanticsDebuggerState();
}

class _SemanticsDebuggerState extends State<SemanticsDebugger> {
  void initState() {
    super.initState();
29 30
    _SemanticsDebuggerListener.ensureInstantiated();
    _SemanticsDebuggerListener.instance.addListener(_update);
Hixie's avatar
Hixie committed
31 32
  }
  void dispose() {
33
    _SemanticsDebuggerListener.instance.removeListener(_update);
Hixie's avatar
Hixie committed
34 35 36 37
    super.dispose();
  }
  void _update() {
    setState(() {
38
      // the generation of the _SemanticsDebuggerListener has changed
Hixie's avatar
Hixie committed
39 40 41 42 43 44 45 46 47 48
    });
  }
  Point _lastPointerDownLocation;
  void _handlePointerDown(PointerDownEvent event) {
    setState(() {
      _lastPointerDownLocation = event.position;
    });
  }
  void _handleTap() {
    assert(_lastPointerDownLocation != null);
49
    _SemanticsDebuggerListener.instance.handleTap(_lastPointerDownLocation);
Hixie's avatar
Hixie committed
50 51 52 53 54 55
    setState(() {
      _lastPointerDownLocation = null;
    });
  }
  void _handleLongPress() {
    assert(_lastPointerDownLocation != null);
56
    _SemanticsDebuggerListener.instance.handleLongPress(_lastPointerDownLocation);
Hixie's avatar
Hixie committed
57 58 59 60
    setState(() {
      _lastPointerDownLocation = null;
    });
  }
61
  void _handlePanEnd(Velocity velocity) {
Hixie's avatar
Hixie committed
62
    assert(_lastPointerDownLocation != null);
63
    _SemanticsDebuggerListener.instance.handlePanEnd(_lastPointerDownLocation, velocity);
Hixie's avatar
Hixie committed
64 65 66 67 68 69
    setState(() {
      _lastPointerDownLocation = null;
    });
  }
  Widget build(BuildContext context) {
    return new CustomPaint(
70
      foregroundPainter: new _SemanticsDebuggerPainter(_SemanticsDebuggerListener.instance.generation, _lastPointerDownLocation),
Hixie's avatar
Hixie committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
      child: new GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: _handleTap,
        onLongPress: _handleLongPress,
        onPanEnd: _handlePanEnd,
        excludeFromSemantics: true, // otherwise if you don't hit anything, we end up receiving it, which causes an infinite loop...
        child: new Listener(
          onPointerDown: _handlePointerDown,
          behavior: HitTestBehavior.opaque,
          child: new IgnorePointer(
            ignoringSemantics: false,
            child: config.child
          )
        )
      )
    );
  }
}

typedef bool _SemanticsDebuggerEntryFilter(_SemanticsDebuggerEntry entry);

class _SemanticsDebuggerEntry {
  _SemanticsDebuggerEntry(this.id);

  final int id;
  bool canBeTapped = false;
  bool canBeLongPressed = false;
  bool canBeScrolledHorizontally = false;
  bool canBeScrolledVertically = false;
  bool hasCheckedState = false;
  bool isChecked = false;
  String label;
  Matrix4 transform;
  Rect rect;
  List<_SemanticsDebuggerEntry> children;

  String toString() {
    return '_SemanticsDebuggerEntry($id; $rect; "$label"'
           '${canBeTapped ? "; canBeTapped" : ""}'
           '${canBeLongPressed ? "; canBeLongPressed" : ""}'
           '${canBeScrolledHorizontally ? "; canBeScrolledHorizontally" : ""}'
           '${canBeScrolledVertically ? "; canBeScrolledVertically" : ""}'
           '${hasCheckedState ? isChecked ? "; checked" : "; unchecked" : ""}'
           ')';
  }
  String toStringDeep([ String prefix = '']) {
    if (prefix.length > 20)
      return '$prefix<ABORTED>\n';
    String result = '$prefix$this\n';
    for (_SemanticsDebuggerEntry child in children.reversed) {
      prefix += '  ';
      result += '${child.toStringDeep(prefix)}';
    }
    return result;
  }

  int findDepth() {
    if (children == null || children.isEmpty)
      return 1;
130 131 132
    return children.map((_SemanticsDebuggerEntry e) => e.findDepth()).reduce((int runningDepth, int nextDepth) {
      return math.max(runningDepth, nextDepth);
    }) + 1;
Hixie's avatar
Hixie committed
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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  }

  static const TextStyle textStyles = const TextStyle(
    color: const Color(0xFF000000),
    fontSize: 10.0,
    height: 0.8,
    textAlign: TextAlign.center
  );

  TextPainter textPainter;
  void updateMessage() {
    List<String> annotations = <String>[];
    bool wantsTap = false;
    if (hasCheckedState) {
      annotations.add(isChecked ? 'checked' : 'unchecked');
      wantsTap = true;
    }
    if (canBeTapped) {
      if (!wantsTap)
        annotations.add('button');
    } else {
      if (wantsTap)
        annotations.add('disabled');
    }
    if (canBeLongPressed)
      annotations.add('long-pressable');
    if (canBeScrolledHorizontally || canBeScrolledVertically)
      annotations.add('scrollable');
    String message;
    if (annotations.isEmpty) {
      assert(label != null);
      message = label;
    } else {
      if (label == '') {
        message = annotations.join('; ');
      } else {
        message = '$label (${annotations.join('; ')})';
      }
    }
    message = message.trim();
    if (message != '') {
      textPainter ??= new TextPainter();
Adam Barth's avatar
Adam Barth committed
175
      textPainter.text = new TextSpan(style: textStyles, text: message);
Hixie's avatar
Hixie committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
      textPainter.maxWidth = rect.width;
      textPainter.maxHeight = rect.height;
      textPainter.layout();
    } else {
      textPainter = null;
    }
  }

  void paint(Canvas canvas, int rank) {
    canvas.save();
    if (transform != null)
      canvas.transform(transform.storage);
    if (!rect.isEmpty) {
      Color lineColor = new Color(0xFF000000 + new math.Random(id).nextInt(0xFFFFFF));
      Rect innerRect = rect.deflate(rank * 1.0);
      if (innerRect.isEmpty) {
        Paint fill = new Paint()
         ..color = lineColor
194
         ..style = PaintingStyle.fill;
Hixie's avatar
Hixie committed
195 196 197 198
        canvas.drawRect(rect, fill);
      } else {
        Paint fill = new Paint()
         ..color = const Color(0xFFFFFFFF)
199
         ..style = PaintingStyle.fill;
Hixie's avatar
Hixie committed
200 201 202 203
        canvas.drawRect(rect, fill);
        Paint line = new Paint()
         ..strokeWidth = rank * 2.0
         ..color = lineColor
204
         ..style = PaintingStyle.stroke;
Hixie's avatar
Hixie committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        canvas.drawRect(innerRect, line);
      }
      if (textPainter != null) {
        canvas.save();
        canvas.clipRect(rect);
        textPainter.paint(canvas, rect.topLeft.toOffset());
        canvas.restore();
      }
    }
    for (_SemanticsDebuggerEntry child in children)
      child.paint(canvas, rank - 1);
    canvas.restore();
  }

  _SemanticsDebuggerEntry hitTest(Point position, _SemanticsDebuggerEntryFilter filter) {
    if (transform != null) {
221 222 223
      Matrix4 invertedTransform = new Matrix4.identity();
      double determinant = invertedTransform.copyInverse(transform);
      if (determinant == 0.0)
Hixie's avatar
Hixie committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        return null;
      position = MatrixUtils.transformPoint(invertedTransform, position);
    }
    if (!rect.contains(position))
      return null;
    _SemanticsDebuggerEntry result;
    for (_SemanticsDebuggerEntry child in children.reversed) {
      result = child.hitTest(position, filter);
      if (result != null)
        break;
    }
    if (result == null || !filter(result))
      result = this;
    return result;
  }
}

241 242
class _SemanticsDebuggerListener implements mojom.SemanticsListener {
  _SemanticsDebuggerListener._() {
243
    SemanticsNode.addListener(this);
Hixie's avatar
Hixie committed
244 245
  }

246
  static _SemanticsDebuggerListener instance;
247 248
  static final SemanticsServer _server = new SemanticsServer();
  static void ensureInstantiated() {
249
    instance ??= new _SemanticsDebuggerListener._();
Hixie's avatar
Hixie committed
250 251 252 253 254 255 256 257 258 259 260 261 262
  }

  Set<VoidCallback> _listeners = new Set<VoidCallback>();
  void addListener(VoidCallback callback) {
    assert(!_listeners.contains(callback));
    _listeners.add(callback);
  }
  void removeListener(VoidCallback callback) {
    _listeners.remove(callback);
  }

  Map<int, _SemanticsDebuggerEntry> nodes = <int, _SemanticsDebuggerEntry>{};

263
  _SemanticsDebuggerEntry _updateNode(mojom.SemanticsNode node) {
Hixie's avatar
Hixie committed
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
    _SemanticsDebuggerEntry entry = nodes.putIfAbsent(node.id, () => new _SemanticsDebuggerEntry(node.id));
    if (node.flags != null) {
      entry.canBeTapped = node.flags.canBeTapped;
      entry.canBeLongPressed = node.flags.canBeLongPressed;
      entry.canBeScrolledHorizontally = node.flags.canBeScrolledHorizontally;
      entry.canBeScrolledVertically = node.flags.canBeScrolledVertically;
      entry.hasCheckedState = node.flags.hasCheckedState;
      entry.isChecked = node.flags.isChecked;
    }
    if (node.strings != null) {
      assert(node.strings.label != null);
      entry.label = node.strings.label;
    } else {
      assert(entry.label != null);
    }
    if (node.geometry != null) {
      if (node.geometry.transform != null) {
        assert(node.geometry.transform.length == 16);
        // TODO(ianh): Replace this with a cleaner call once
        //  https://github.com/google/vector_math.dart/issues/159
        // is fixed.
        List<double> array = node.geometry.transform;
        entry.transform = new Matrix4(
          array[0],  array[1],  array[2],  array[3],
          array[4],  array[5],  array[6],  array[7],
          array[8],  array[9],  array[10], array[11],
          array[12], array[13], array[14], array[15]
        );
      } else {
        entry.transform = null;
      }
      entry.rect = new Rect.fromLTWH(node.geometry.left, node.geometry.top, node.geometry.width, node.geometry.height);
    }
    entry.updateMessage();
    if (node.children != null) {
      Set oldChildren = new Set<_SemanticsDebuggerEntry>.from(entry.children ?? const <_SemanticsDebuggerEntry>[]);
      entry.children?.clear();
      entry.children ??= new List<_SemanticsDebuggerEntry>();
302
      for (mojom.SemanticsNode child in node.children)
Hixie's avatar
Hixie committed
303 304 305 306 307 308 309 310 311 312 313
        entry.children.add(_updateNode(child));
      Set newChildren = new Set<_SemanticsDebuggerEntry>.from(entry.children);
      Set<_SemanticsDebuggerEntry> removedChildren = oldChildren.difference(newChildren);
      for (_SemanticsDebuggerEntry oldChild in removedChildren)
        nodes.remove(oldChild.id);
    }
    return entry;
  }

  int generation = 0;

314
  updateSemanticsTree(List<mojom.SemanticsNode> nodes) {
Hixie's avatar
Hixie committed
315
    generation += 1;
316
    for (mojom.SemanticsNode node in nodes)
Hixie's avatar
Hixie committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
      _updateNode(node);
    for (VoidCallback listener in _listeners)
      listener();
  }

  _SemanticsDebuggerEntry _hitTest(Point position, _SemanticsDebuggerEntryFilter filter) {
    return nodes[0]?.hitTest(position, filter);
  }

  void handleTap(Point position) {
    _server.tap(_hitTest(position, (_SemanticsDebuggerEntry entry) => entry.canBeTapped)?.id ?? 0);
  }
  void handleLongPress(Point position) {
    _server.longPress(_hitTest(position, (_SemanticsDebuggerEntry entry) => entry.canBeLongPressed)?.id ?? 0);
  }
332 333 334 335
  void handlePanEnd(Point position, Velocity velocity) {
    double vx = velocity.pixelsPerSecond.dx;
    double vy = velocity.pixelsPerSecond.dy;
    if (vx.abs() == vy.abs())
Hixie's avatar
Hixie committed
336
      return;
337 338
    if (vx.abs() > vy.abs()) {
      if (vx.sign < 0)
Hixie's avatar
Hixie committed
339 340 341 342
        _server.scrollLeft(_hitTest(position, (_SemanticsDebuggerEntry entry) => entry.canBeScrolledHorizontally)?.id ?? 0);
      else
        _server.scrollRight(_hitTest(position, (_SemanticsDebuggerEntry entry) => entry.canBeScrolledHorizontally)?.id ?? 0);
    } else {
343
      if (vy.sign < 0)
Hixie's avatar
Hixie committed
344 345 346 347 348 349 350 351 352 353 354 355
        _server.scrollUp(_hitTest(position, (_SemanticsDebuggerEntry entry) => entry.canBeScrolledVertically)?.id ?? 0);
      else
        _server.scrollDown(_hitTest(position, (_SemanticsDebuggerEntry entry) => entry.canBeScrolledVertically)?.id ?? 0);
    }
  }
}

class _SemanticsDebuggerPainter extends CustomPainter {
  const _SemanticsDebuggerPainter(this.generation, this.pointerPosition);
  final int generation;
  final Point pointerPosition;
  void paint(Canvas canvas, Size size) {
356
    _SemanticsDebuggerListener.instance.nodes[0]?.paint(
357
      canvas,
358
      _SemanticsDebuggerListener.instance.nodes[0].findDepth()
Hixie's avatar
Hixie committed
359 360 361 362 363 364 365 366 367 368 369 370
    );
    if (pointerPosition != null) {
      Paint paint = new Paint();
      paint.color = const Color(0x7F0090FF);
      canvas.drawCircle(pointerPosition, 10.0, paint);
    }
  }
  bool shouldRepaint(_SemanticsDebuggerPainter oldDelegate) {
    return generation != oldDelegate.generation
        || pointerPosition != oldDelegate.pointerPosition;
  }
}