summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/accessibility/accessible.js
blob: 1866d0a91b7b926dc144070f23af1568884371a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const { Actor } = require("resource://devtools/shared/protocol.js");
const {
  accessibleSpec,
} = require("resource://devtools/shared/specs/accessibility.js");

const {
  accessibility: { AUDIT_TYPE },
} = require("resource://devtools/shared/constants.js");

loader.lazyRequireGetter(
  this,
  "getContrastRatioFor",
  "resource://devtools/server/actors/accessibility/audit/contrast.js",
  true
);
loader.lazyRequireGetter(
  this,
  "auditKeyboard",
  "resource://devtools/server/actors/accessibility/audit/keyboard.js",
  true
);
loader.lazyRequireGetter(
  this,
  "auditTextLabel",
  "resource://devtools/server/actors/accessibility/audit/text-label.js",
  true
);
loader.lazyRequireGetter(
  this,
  "isDefunct",
  "resource://devtools/server/actors/utils/accessibility.js",
  true
);
loader.lazyRequireGetter(
  this,
  "findCssSelector",
  "resource://devtools/shared/inspector/css-logic.js",
  true
);
loader.lazyRequireGetter(
  this,
  "events",
  "resource://devtools/shared/event-emitter.js"
);
loader.lazyRequireGetter(
  this,
  "getBounds",
  "resource://devtools/server/actors/highlighters/utils/accessibility.js",
  true
);
loader.lazyRequireGetter(
  this,
  "isFrameWithChildTarget",
  "resource://devtools/shared/layout/utils.js",
  true
);
const lazy = {};
loader.lazyGetter(
  lazy,
  "ContentDOMReference",
  () =>
    ChromeUtils.importESModule(
      "resource://gre/modules/ContentDOMReference.sys.mjs",
      {
        // ContentDOMReference needs to be retrieved from the shared global
        // since it is a shared singleton.
        loadInDevToolsLoader: false,
      }
    ).ContentDOMReference
);

const RELATIONS_TO_IGNORE = new Set([
  Ci.nsIAccessibleRelation.RELATION_CONTAINING_APPLICATION,
  Ci.nsIAccessibleRelation.RELATION_CONTAINING_TAB_PANE,
  Ci.nsIAccessibleRelation.RELATION_CONTAINING_WINDOW,
  Ci.nsIAccessibleRelation.RELATION_PARENT_WINDOW_OF,
  Ci.nsIAccessibleRelation.RELATION_SUBWINDOW_OF,
]);

const nsIAccessibleRole = Ci.nsIAccessibleRole;
const TEXT_ROLES = new Set([
  nsIAccessibleRole.ROLE_TEXT_LEAF,
  nsIAccessibleRole.ROLE_STATICTEXT,
]);

const STATE_DEFUNCT = Ci.nsIAccessibleStates.EXT_STATE_DEFUNCT;
const CSS_TEXT_SELECTOR = "#text";

/**
 * Get node inforamtion such as nodeType and the unique CSS selector for the node.
 * @param  {DOMNode} node
 *         Node for which to get the information.
 * @return {Object}
 *         Information about the type of the node and how to locate it.
 */
function getNodeDescription(node) {
  if (!node || Cu.isDeadWrapper(node)) {
    return { nodeType: undefined, nodeCssSelector: "" };
  }

  const { nodeType } = node;
  return {
    nodeType,
    // If node is a text node, we find a unique CSS selector for its parent and add a
    // CSS_TEXT_SELECTOR postfix to indicate that it's a text node.
    nodeCssSelector:
      nodeType === Node.TEXT_NODE
        ? `${findCssSelector(node.parentNode)}${CSS_TEXT_SELECTOR}`
        : findCssSelector(node),
  };
}

/**
 * Get a snapshot of the nsIAccessible object including its subtree. None of the subtree
 * queried here is cached via accessible walker's refMap.
 * @param  {nsIAccessible} acc
 *         Accessible object to take a snapshot of.
 * @param  {nsIAccessibilityService} a11yService
 *         Accessibility service instance in the current process, used to get localized
 *         string representation of various accessible properties.
 * @param  {WindowGlobalTargetActor} targetActor
 * @return {JSON}
 *         JSON snapshot of the accessibility tree with root at current accessible.
 */
function getSnapshot(acc, a11yService, targetActor) {
  if (isDefunct(acc)) {
    return {
      states: [a11yService.getStringStates(0, STATE_DEFUNCT)],
    };
  }

  const actions = [];
  for (let i = 0; i < acc.actionCount; i++) {
    actions.push(acc.getActionDescription(i));
  }

  const attributes = {};
  if (acc.attributes) {
    for (const { key, value } of acc.attributes.enumerate()) {
      attributes[key] = value;
    }
  }

  const state = {};
  const extState = {};
  acc.getState(state, extState);
  const states = [...a11yService.getStringStates(state.value, extState.value)];

  const children = [];
  for (let child = acc.firstChild; child; child = child.nextSibling) {
    // Ignore children from different documents when we have targets for every documents.
    if (
      targetActor.ignoreSubFrames &&
      child.DOMNode.ownerDocument !== targetActor.contentDocument
    ) {
      continue;
    }
    children.push(getSnapshot(child, a11yService, targetActor));
  }

  const { nodeType, nodeCssSelector } = getNodeDescription(acc.DOMNode);
  const snapshot = {
    name: acc.name,
    role: getStringRole(acc, a11yService),
    actions,
    value: acc.value,
    nodeCssSelector,
    nodeType,
    description: acc.description,
    keyboardShortcut: acc.accessKey || acc.keyboardShortcut,
    childCount: acc.childCount,
    indexInParent: acc.indexInParent,
    states,
    children,
    attributes,
  };
  const useChildTargetToFetchChildren =
    acc.role === Ci.nsIAccessibleRole.ROLE_INTERNAL_FRAME &&
    isFrameWithChildTarget(targetActor, acc.DOMNode);
  if (useChildTargetToFetchChildren) {
    snapshot.useChildTargetToFetchChildren = useChildTargetToFetchChildren;
    snapshot.childCount = 1;
    snapshot.contentDOMReference = lazy.ContentDOMReference.get(acc.DOMNode);
  }

  return snapshot;
}

/**
 * Get a string indicating the role of the nsIAccessible object.
 * An ARIA role token will be returned unless the role can't be mapped to an
 * ARIA role (e.g. <iframe>), in which case a Gecko role string will be
 * returned.
 * @param  {nsIAccessible} acc
 *         Accessible object to take a snapshot of.
 * @param  {nsIAccessibilityService} a11yService
 *         Accessibility service instance in the current process, used to get localized
 *         string representation of various accessible properties.
 * @return String
 */
function getStringRole(acc, a11yService) {
  let role = acc.computedARIARole;
  if (!role) {
    // We couldn't map to an ARIA role, so use a Gecko role string.
    role = a11yService.getStringRole(acc.role);
  }
  return role;
}

/**
 * The AccessibleActor provides information about a given accessible object: its
 * role, name, states, etc.
 */
class AccessibleActor extends Actor {
  constructor(walker, rawAccessible) {
    super(walker.conn, accessibleSpec);
    this.walker = walker;
    this.rawAccessible = rawAccessible;

    /**
     * Indicates if the raw accessible is no longer alive.
     *
     * @return Boolean
     */
    Object.defineProperty(this, "isDefunct", {
      get() {
        const defunct = isDefunct(this.rawAccessible);
        if (defunct) {
          delete this.isDefunct;
          this.isDefunct = true;
          return this.isDefunct;
        }

        return defunct;
      },
      configurable: true,
    });
  }

  destroy() {
    super.destroy();
    this.walker = null;
    this.rawAccessible = null;
  }

  get role() {
    if (this.isDefunct) {
      return null;
    }
    return getStringRole(this.rawAccessible, this.walker.a11yService);
  }

  get name() {
    if (this.isDefunct) {
      return null;
    }
    return this.rawAccessible.name;
  }

  get value() {
    if (this.isDefunct) {
      return null;
    }
    return this.rawAccessible.value;
  }

  get description() {
    if (this.isDefunct) {
      return null;
    }
    return this.rawAccessible.description;
  }

  get keyboardShortcut() {
    if (this.isDefunct) {
      return null;
    }
    // Gecko accessibility exposes two key bindings: Accessible::AccessKey and
    // Accessible::KeyboardShortcut. The former is used for accesskey, where the latter
    // is used for global shortcuts defined by XUL menu items, etc. Here - do what the
    // Windows implementation does: try AccessKey first, and if that's empty, use
    // KeyboardShortcut.
    return this.rawAccessible.accessKey || this.rawAccessible.keyboardShortcut;
  }

  get childCount() {
    if (this.isDefunct) {
      return 0;
    }
    // In case of a remote frame declare at least one child (the #document
    // element) so that they can be expanded.
    if (this.useChildTargetToFetchChildren) {
      return 1;
    }

    return this.rawAccessible.childCount;
  }

  get domNodeType() {
    if (this.isDefunct) {
      return 0;
    }
    return this.rawAccessible.DOMNode ? this.rawAccessible.DOMNode.nodeType : 0;
  }

  get parentAcc() {
    if (this.isDefunct) {
      return null;
    }
    return this.walker.addRef(this.rawAccessible.parent);
  }

  children() {
    const children = [];
    if (this.isDefunct) {
      return children;
    }

    for (
      let child = this.rawAccessible.firstChild;
      child;
      child = child.nextSibling
    ) {
      children.push(this.walker.addRef(child));
    }
    return children;
  }

  get indexInParent() {
    if (this.isDefunct) {
      return -1;
    }

    try {
      return this.rawAccessible.indexInParent;
    } catch (e) {
      // Accessible is dead.
      return -1;
    }
  }

  get actions() {
    const actions = [];
    if (this.isDefunct) {
      return actions;
    }

    for (let i = 0; i < this.rawAccessible.actionCount; i++) {
      actions.push(this.rawAccessible.getActionDescription(i));
    }
    return actions;
  }

  get states() {
    if (this.isDefunct) {
      return [];
    }

    const state = {};
    const extState = {};
    this.rawAccessible.getState(state, extState);
    return [
      ...this.walker.a11yService.getStringStates(state.value, extState.value),
    ];
  }

  get attributes() {
    if (this.isDefunct || !this.rawAccessible.attributes) {
      return {};
    }

    const attributes = {};
    for (const { key, value } of this.rawAccessible.attributes.enumerate()) {
      attributes[key] = value;
    }

    return attributes;
  }

  get bounds() {
    if (this.isDefunct) {
      return null;
    }

    let x = {},
      y = {},
      w = {},
      h = {};
    try {
      this.rawAccessible.getBoundsInCSSPixels(x, y, w, h);
      x = x.value;
      y = y.value;
      w = w.value;
      h = h.value;
    } catch (e) {
      return null;
    }

    // Check if accessible bounds are invalid.
    const left = x,
      right = x + w,
      top = y,
      bottom = y + h;
    if (left === right || top === bottom) {
      return null;
    }

    return { x, y, w, h };
  }

  async getRelations() {
    const relationObjects = [];
    if (this.isDefunct) {
      return relationObjects;
    }

    const relations = [
      ...this.rawAccessible.getRelations().enumerate(Ci.nsIAccessibleRelation),
    ];
    if (relations.length === 0) {
      return relationObjects;
    }

    const doc = await this.walker.getDocument();
    if (this.isDestroyed()) {
      // This accessible actor is destroyed.
      return relationObjects;
    }
    relations.forEach(relation => {
      if (RELATIONS_TO_IGNORE.has(relation.relationType)) {
        return;
      }

      const type = this.walker.a11yService.getStringRelationType(
        relation.relationType
      );
      const targets = [...relation.getTargets().enumerate(Ci.nsIAccessible)];
      let relationObject;
      for (const target of targets) {
        let targetAcc;
        try {
          targetAcc = this.walker.attachAccessible(target, doc.rawAccessible);
        } catch (e) {
          // Target is not available.
        }

        if (targetAcc) {
          if (!relationObject) {
            relationObject = { type, targets: [] };
          }

          relationObject.targets.push(targetAcc);
        }
      }

      if (relationObject) {
        relationObjects.push(relationObject);
      }
    });

    return relationObjects;
  }

  get useChildTargetToFetchChildren() {
    if (this.isDefunct) {
      return false;
    }

    return (
      this.rawAccessible.role === Ci.nsIAccessibleRole.ROLE_INTERNAL_FRAME &&
      isFrameWithChildTarget(
        this.walker.targetActor,
        this.rawAccessible.DOMNode
      )
    );
  }

  form() {
    return {
      actor: this.actorID,
      role: this.role,
      name: this.name,
      useChildTargetToFetchChildren: this.useChildTargetToFetchChildren,
      childCount: this.childCount,
      checks: this._lastAudit,
    };
  }

  /**
   * Provide additional (full) information about the accessible object that is
   * otherwise missing from the form.
   *
   * @return {Object}
   *         Object that contains accessible object information such as states,
   *         actions, attributes, etc.
   */
  hydrate() {
    return {
      value: this.value,
      description: this.description,
      keyboardShortcut: this.keyboardShortcut,
      domNodeType: this.domNodeType,
      indexInParent: this.indexInParent,
      states: this.states,
      actions: this.actions,
      attributes: this.attributes,
    };
  }

  _isValidTextLeaf(rawAccessible) {
    return (
      !isDefunct(rawAccessible) &&
      TEXT_ROLES.has(rawAccessible.role) &&
      rawAccessible.name &&
      !!rawAccessible.name.trim().length
    );
  }

  /**
   * Calculate the contrast ratio of the given accessible.
   */
  async _getContrastRatio() {
    if (!this._isValidTextLeaf(this.rawAccessible)) {
      return null;
    }

    const { bounds } = this;
    if (!bounds) {
      return null;
    }

    const { DOMNode: rawNode } = this.rawAccessible;
    const win = rawNode.ownerGlobal;

    // Keep the reference to the walker actor in case the actor gets destroyed
    // during the colour contrast ratio calculation.
    const { walker } = this;
    await walker.clearStyles(win);
    const contrastRatio = await getContrastRatioFor(rawNode.parentNode, {
      bounds: getBounds(win, bounds),
      win,
      appliedColorMatrix: this.walker.colorMatrix,
    });

    if (this.isDestroyed()) {
      // This accessible actor is destroyed.
      return null;
    }
    await walker.restoreStyles(win);

    return contrastRatio;
  }

  /**
   * Run an accessibility audit for a given audit type.
   * @param {String} type
   *        Type of an audit (Check AUDIT_TYPE in devtools/shared/constants
   *        to see available audit types).
   *
   * @return {null|Object}
   *         Object that contains accessible audit data for a given type or null
   *         if there's nothing to report for this accessible.
   */
  _getAuditByType(type) {
    switch (type) {
      case AUDIT_TYPE.CONTRAST:
        return this._getContrastRatio();
      case AUDIT_TYPE.KEYBOARD:
        // Determine if keyboard accessibility is lacking where it is necessary.
        return auditKeyboard(this.rawAccessible);
      case AUDIT_TYPE.TEXT_LABEL:
        // Determine if text alternative is missing for an accessible where it
        // is necessary.
        return auditTextLabel(this.rawAccessible);
      default:
        return null;
    }
  }

  /**
   * Audit the state of the accessible object.
   *
   * @param  {Object} options
   *         Options for running audit, may include:
   *         - types: Array of audit types to be performed during audit.
   *
   * @return {Object|null}
   *         Audit results for the accessible object.
   */
  audit(options = {}) {
    if (this._auditing) {
      return this._auditing;
    }

    const { types } = options;
    let auditTypes = Object.values(AUDIT_TYPE);
    if (types && types.length) {
      auditTypes = auditTypes.filter(auditType => types.includes(auditType));
    }

    // For some reason keyboard checks for focus styling affect values (that are
    // used by other types of checks (text names and values)) returned by
    // accessible objects. This happens only when multiple checks are run at the
    // same time (asynchronously) and the audit might return unexpected
    // failures. We thus split the execution of the checks into two parts, first
    // performing keyboard checks and only after the rest of the checks. See bug
    // 1594743 for more detail.
    let keyboardAuditResult;
    const keyboardAuditIndex = auditTypes.indexOf(AUDIT_TYPE.KEYBOARD);
    if (keyboardAuditIndex > -1) {
      // If we are performing a keyboard audit, remove its value from the
      // complete list and run it.
      auditTypes.splice(keyboardAuditIndex, 1);
      keyboardAuditResult = this._getAuditByType(AUDIT_TYPE.KEYBOARD);
    }

    this._auditing = Promise.resolve(keyboardAuditResult)
      .then(keyboardResult => {
        const audits = auditTypes.map(auditType =>
          this._getAuditByType(auditType)
        );

        // If we are also performing a keyboard audit, add its type and its
        // result back to the complete list of audits.
        if (keyboardAuditIndex > -1) {
          auditTypes.splice(keyboardAuditIndex, 0, AUDIT_TYPE.KEYBOARD);
          audits.splice(keyboardAuditIndex, 0, keyboardResult);
        }

        return Promise.all(audits);
      })
      .then(results => {
        if (this.isDefunct || this.isDestroyed()) {
          return null;
        }

        const audit = results.reduce((auditResults, result, index) => {
          auditResults[auditTypes[index]] = result;
          return auditResults;
        }, {});
        this._lastAudit = this._lastAudit || {};
        Object.assign(this._lastAudit, audit);
        events.emit(this, "audited", audit);

        return audit;
      })
      .catch(error => {
        if (!this.isDefunct && !this.isDestroyed()) {
          throw error;
        }
        return null;
      })
      .finally(() => {
        this._auditing = null;
      });

    return this._auditing;
  }

  snapshot() {
    return getSnapshot(
      this.rawAccessible,
      this.walker.a11yService,
      this.walker.targetActor
    );
  }
}

exports.AccessibleActor = AccessibleActor;