forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoutput.js
1513 lines (1353 loc) · 47.7 KB
/
output.js
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
676
677
678
679
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Provides output services for ChromeVox.
*/
import {AutomationPredicate} from '/common/automation_predicate.js';
import {AutomationUtil} from '/common/automation_util.js';
import {constants} from '/common/constants.js';
import {Cursor, CURSOR_NODE_INDEX} from '/common/cursors/cursor.js';
import {CursorRange} from '/common/cursors/range.js';
import {NavBraille} from '../../common/braille/nav_braille.js';
import {EarconId} from '../../common/earcon_id.js';
import {EventSourceType} from '../../common/event_source_type.js';
import {LocaleOutputHelper} from '../../common/locale_output_helper.js';
import {LogType} from '../../common/log_types.js';
import {Msgs} from '../../common/msgs.js';
import {CustomRole} from '../../common/role_type.js';
import {SettingsManager} from '../../common/settings_manager.js';
import {Spannable} from '../../common/spannable.js';
import {QueueMode, TtsCategory, TtsSpeechProperties} from '../../common/tts_types.js';
import {ValueSelectionSpan, ValueSpan} from '../braille/spans.js';
import {ChromeVox} from '../chromevox.js';
import {EventSource} from '../event_source.js';
import {FocusBounds} from '../focus_bounds.js';
import {OutputAncestryInfo} from './output_ancestry_info.js';
import {OutputFormatParser, OutputFormatParserObserver} from './output_format_parser.js';
import {OutputFormatTree} from './output_format_tree.js';
import {OutputFormatter} from './output_formatter.js';
import {OutputInterface} from './output_interface.js';
import {OutputFormatLogger} from './output_logger.js';
import {OutputRoleInfo} from './output_role_info.js';
import {AncestryOutputRule, OutputRule, OutputRuleSpecifier} from './output_rules.js';
import * as outputTypes from './output_types.js';
const AriaCurrentState = chrome.automation.AriaCurrentState;
const AutomationNode = chrome.automation.AutomationNode;
const DescriptionFromType = chrome.automation.DescriptionFromType;
const Dir = constants.Dir;
const EventType = chrome.automation.EventType;
const NameFromType = chrome.automation.NameFromType;
const Restriction = chrome.automation.Restriction;
const RoleType = chrome.automation.RoleType;
const StateType = chrome.automation.StateType;
/**
* An Output object formats a CursorRange into speech, braille, or both
* representations. This is typically a |Spannable|.
* The translation from Range to these output representations rely upon format
* rules which specify how to convert AutomationNode objects into annotated
* strings.
* The format of these rules is as follows.
* $ prefix: used to substitute either an attribute or a specialized value from
* an AutomationNode. Specialized values include role and state.
* For example, $value $role $enabled
*
* Note: (@) means @ to avoid Closure mistaking it for an annotation.
*
* (@) prefix: used to substitute a message. Note the ability to specify params
* to the message. For example, '@tag_html' '@selected_index($text_sel_start,
* $text_sel_end').
*
* (@@) prefix: similar to @, used to substitute a message, but also pulls the
* localized string through goog.i18n.MessageFormat to support locale
* aware plural handling. The first argument should be a number which will
* be passed as a COUNT named parameter to MessageFormat.
* TODO(plundblad): Make subsequent arguments normal placeholder arguments
* when needed.
* = suffix: used to specify substitution only if not previously appended.
* For example, $name= would insert the name attribute only if no name
* attribute had been inserted previously.
* @implements {OutputInterface}
*/
export class Output {
constructor() {
// TODO(dtseng): Include braille specific rules.
/** @private {!Array<!Spannable>} */
this.speechBuffer_ = [];
/** @private {!Array<!Spannable>} */
this.brailleBuffer_ = [];
/** @private {!Array<!Object>} */
this.locations_ = [];
/** @private {function(boolean=)} */
this.speechEndCallback_;
// Store output rules.
/** @private {!OutputFormatLogger} */
this.speechFormatLog_ =
new OutputFormatLogger('enableSpeechLogging', LogType.SPEECH_RULE);
/** @private {!OutputFormatLogger} */
this.brailleFormatLog_ =
new OutputFormatLogger('enableBrailleLogging', LogType.BRAILLE_RULE);
/**
* Current global options.
* @private {{speech: boolean, braille: boolean, auralStyle: boolean}}
*/
this.formatOptions_ = {speech: true, braille: false, auralStyle: false};
/**
* The speech category for the generated speech utterance.
* @private {TtsCategory}
*/
this.speechCategory_ = TtsCategory.NAV;
/**
* The speech queue mode for the generated speech utterance.
* @private {QueueMode}
*/
this.queueMode_;
/** @private {!outputTypes.OutputContextOrder} */
this.contextOrder_ = outputTypes.OutputContextOrder.LAST;
/** @private {!Object<string, boolean>} */
this.suppressions_ = {};
/** @private {boolean} */
this.enableHints_ = true;
/** @private {!TtsSpeechProperties} */
this.initialSpeechProps_ = new TtsSpeechProperties();
/** @private {boolean} */
this.drawFocusRing_ = true;
/**
* Tracks all ancestors which have received primary formatting in
* |ancestryHelper_|.
* @private {!WeakSet<!AutomationNode>}
*/
this.formattedAncestors_ = new WeakSet();
/** @private {!Object<string, string>} */
this.replacements_ = {};
}
/**
* Calling this will make the next speech utterance use |mode| even if it
* would normally queue or do a category flush. This differs from the
* |withQueueMode| instance method as it can apply to future output.
* @param {QueueMode|undefined} mode
*/
static forceModeForNextSpeechUtterance(mode) {
if (Output.forceModeForNextSpeechUtterance_ === undefined ||
mode === undefined ||
// Only allow setting to higher queue modes.
mode < Output.forceModeForNextSpeechUtterance_) {
Output.forceModeForNextSpeechUtterance_ = mode;
}
}
/** @return {boolean} True if there's any speech that will be output. */
get hasSpeech() {
return this.speechBuffer_.some(speech => speech.length);
}
/** @return {boolean} True if there is only whitespace in this output. */
get isOnlyWhitespace() {
return this.speechBuffer_.every(buff => !/\S+/.test(buff.toString()));
}
/** @return {Spannable} */
get braille() {
return this.mergeBraille_(this.brailleBuffer_);
}
/**
* Specify ranges for speech.
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @return {!Output}
*/
withSpeech(range, prevRange, type) {
this.formatOptions_ = {speech: true, braille: false, auralStyle: false};
this.formattedAncestors_ = new WeakSet();
this.render(
range, prevRange, type, this.speechBuffer_, this.speechFormatLog_);
return this;
}
/**
* Specify ranges for aurally styled speech.
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @return {!Output}
*/
withRichSpeech(range, prevRange, type) {
this.formatOptions_ = {speech: true, braille: false, auralStyle: true};
this.formattedAncestors_ = new WeakSet();
this.render(
range, prevRange, type, this.speechBuffer_, this.speechFormatLog_);
return this;
}
/**
* Specify ranges for braille.
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @return {!Output}
*/
withBraille(range, prevRange, type) {
this.formatOptions_ = {speech: false, braille: true, auralStyle: false};
this.formattedAncestors_ = new WeakSet();
// Braille sometimes shows contextual information depending on role.
if (range.start.equals(range.end) && range.start.node &&
AutomationPredicate.contextualBraille(range.start.node) &&
range.start.node.parent) {
let start = range.start.node.parent;
while (start.firstChild) {
start = start.firstChild;
}
let end = range.start.node.parent;
while (end.lastChild) {
end = end.lastChild;
}
prevRange = CursorRange.fromNode(range.start.node.parent);
range = new CursorRange(Cursor.fromNode(start), Cursor.fromNode(end));
}
this.render(
range, prevRange, type, this.brailleBuffer_, this.brailleFormatLog_);
return this;
}
/**
* Specify ranges for location.
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @return {!Output}
*/
withLocation(range, prevRange, type) {
this.formatOptions_ = {speech: false, braille: false, auralStyle: false};
this.formattedAncestors_ = new WeakSet();
this.render(
range, prevRange, type, [] /*unused output*/,
new OutputFormatLogger('', LogType.SPEECH_RULE) /*unused log*/);
return this;
}
/**
* Specify the same ranges for speech and braille.
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @return {!Output}
*/
withSpeechAndBraille(range, prevRange, type) {
this.withSpeech(range, prevRange, type);
this.withBraille(range, prevRange, type);
return this;
}
/**
* Specify the same ranges for aurally styled speech and braille.
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @return {!Output}
*/
withRichSpeechAndBraille(range, prevRange, type) {
this.withRichSpeech(range, prevRange, type);
this.withBraille(range, prevRange, type);
return this;
}
/**
* Applies the given speech category to the output.
* @param {TtsCategory} category
* @return {!Output}
*/
withSpeechCategory(category) {
this.speechCategory_ = category;
return this;
}
/**
* Applies the given speech queue mode to the output.
* @param {QueueMode} queueMode The queueMode for the speech.
* @return {!Output}
*/
withQueueMode(queueMode) {
this.queueMode_ = queueMode;
return this;
}
/**
* Output a string literal.
* @param {string} value
* @return {!Output}
*/
withString(value) {
this.append(this.speechBuffer_, value);
this.append(this.brailleBuffer_, value);
this.speechFormatLog_.write('withString: ' + value + '\n');
this.brailleFormatLog_.write('withString: ' + value + '\n');
return this;
}
/**
* Outputs formatting nodes after this will contain context first.
* @return {!Output}
*/
withContextFirst() {
this.contextOrder_ = outputTypes.OutputContextOrder.FIRST;
return this;
}
/**
* Don't include hints in subsequent output.
* @return {!Output}
*/
withoutHints() {
this.enableHints_ = false;
return this;
}
/**
* Don't draw a focus ring based on this output.
* @return {!Output}
*/
withoutFocusRing() {
this.drawFocusRing_ = false;
return this;
}
/**
* Supply initial speech properties that will be applied to all output.
* @param {!TtsSpeechProperties} speechProps
* @return {!Output}
*/
withInitialSpeechProperties(speechProps) {
this.initialSpeechProps_ = speechProps;
return this;
}
/**
* Causes any speech output to apply the replacement.
* @param {string} text The text to be replaced.
* @param {string} replace What to replace |text| with.
*/
withSpeechTextReplacement(text, replace) {
this.replacements_[text] = replace;
}
/**
* Suppresses processing of a token for subsequent formatting commands.
* @param {string} token
* @return {!Output}
*/
suppress(token) {
this.suppressions_[token] = true;
return this;
}
/**
* Apply a format string directly to the output buffer. This lets you
* output a message directly to the buffer using the format syntax.
* @param {string} formatStr
* @param {!AutomationNode=} opt_node An optional node to apply the
* formatting to.
* @return {!Output} |this| for chaining
*/
format(formatStr, opt_node) {
return this.formatForSpeech(formatStr, opt_node)
.formatForBraille(formatStr, opt_node);
}
/**
* Apply a format string directly to the speech output buffer. This lets you
* output a message directly to the buffer using the format syntax.
* @param {string} formatStr
* @param {!AutomationNode=} opt_node An optional node to apply the
* formatting to.
* @return {!Output} |this| for chaining
*/
formatForSpeech(formatStr, opt_node) {
const node = opt_node || null;
this.formatOptions_ = {speech: true, braille: false, auralStyle: false};
this.formattedAncestors_ = new WeakSet();
OutputFormatter.format(this, {
node,
outputFormat: formatStr,
outputBuffer: this.speechBuffer_,
outputFormatLogger: this.speechFormatLog_,
});
return this;
}
/**
* Apply a format string directly to the braille output buffer. This lets you
* output a message directly to the buffer using the format syntax.
* @param {string} formatStr
* @param {!AutomationNode=} opt_node An optional node to apply the
* formatting to.
* @return {!Output} |this| for chaining
*/
formatForBraille(formatStr, opt_node) {
const node = opt_node || null;
this.formatOptions_ = {speech: false, braille: true, auralStyle: false};
this.formattedAncestors_ = new WeakSet();
OutputFormatter.format(this, {
node,
outputFormat: formatStr,
outputBuffer: this.brailleBuffer_,
outputFormatLogger: this.brailleFormatLog_,
});
return this;
}
/**
* Triggers callback for a speech event.
* @param {function()} callback
* @return {!Output}
*/
onSpeechEnd(callback) {
this.speechEndCallback_ =
/** @type {function(boolean=)} */ (opt_cleanupOnly => {
if (!opt_cleanupOnly) {
callback();
}
});
return this;
}
/** Executes all specified output. */
go() {
// Speech.
let queueMode = this.determineQueueMode_();
let encounteredNonWhitespace = false;
for (let i = 0; i < this.speechBuffer_.length; i++) {
const buff = this.speechBuffer_[i];
const text = buff.toString();
// Consider empty strings as non-whitespace; they often have earcons
// associated with them, so need to be "spoken".
const isNonWhitespace = text === '' || /\S+/.test(text);
encounteredNonWhitespace = isNonWhitespace || encounteredNonWhitespace;
// Skip whitespace if we've already encountered non-whitespace. This
// prevents output like 'foo', 'space', 'bar'.
if (!isNonWhitespace && encounteredNonWhitespace) {
continue;
}
const speechProps = this.getSpeechPropsForBuff_(buff);
if (i === this.speechBuffer_.length - 1) {
speechProps.endCallback = this.speechEndCallback_;
}
let finalSpeech = buff.toString();
for (const text in this.replacements_) {
finalSpeech = finalSpeech.replace(text, this.replacements_[text]);
}
ChromeVox.tts.speak(finalSpeech, queueMode, speechProps);
// Skip resetting |queueMode| if the |text| is empty. If we don't do this,
// and the tts engine doesn't generate a callback, we might not properly
// flush.
if (text !== '') {
queueMode = QueueMode.QUEUE;
}
}
this.speechFormatLog_.commitLogs();
// Braille.
if (this.brailleBuffer_.length) {
const buff = this.mergeBraille_(this.brailleBuffer_);
const selSpan = buff.getSpanInstanceOf(outputTypes.OutputSelectionSpan);
let startIndex = -1;
let endIndex = -1;
if (selSpan) {
const valueStart = buff.getSpanStart(selSpan);
const valueEnd = buff.getSpanEnd(selSpan);
startIndex = valueStart + selSpan.startIndex;
endIndex = valueStart + selSpan.endIndex;
try {
buff.setSpan(new ValueSpan(0), valueStart, valueEnd);
buff.setSpan(new ValueSelectionSpan(), startIndex, endIndex);
} catch (e) {
}
}
const output = new NavBraille({text: buff, startIndex, endIndex});
ChromeVox.braille.write(output);
this.brailleFormatLog_.commitLogs();
}
// Display.
if (this.speechCategory_ !== TtsCategory.LIVE && this.drawFocusRing_) {
FocusBounds.set(this.locations_);
}
}
/** @return {QueueMode} */
determineQueueMode_() {
if (Output.forceModeForNextSpeechUtterance_ !== undefined) {
const result = Output.forceModeForNextSpeechUtterance_;
if (this.speechBuffer_.length > 0) {
Output.forceModeForNextSpeechUtterance_ = undefined;
}
return result;
}
if (this.queueMode_ !== undefined) {
return this.queueMode_;
}
return QueueMode.QUEUE;
}
/**
* @param {!Spannable} buff
* @return {!TtsSpeechProperties}
*/
getSpeechPropsForBuff_(buff) {
let speechProps;
const speechPropsInstance =
/** @type {outputTypes.OutputSpeechProperties} */ (
buff.getSpanInstanceOf(outputTypes.OutputSpeechProperties));
if (!speechPropsInstance) {
speechProps = this.initialSpeechProps_;
} else {
for (const [key, value] of Object.entries(this.initialSpeechProps_)) {
if (speechPropsInstance.properties[key] === undefined) {
speechPropsInstance.properties[key] = value;
}
}
speechProps = new TtsSpeechProperties(speechPropsInstance.properties);
}
speechProps.category = this.speechCategory_;
speechProps.startCallback = () => {
const actions = buff.getSpansInstanceOf(outputTypes.OutputAction);
if (actions) {
actions.forEach(action => action.run());
}
};
return speechProps;
}
/**
* @return {boolean} True if this object is equal to |rhs|.
*/
equals(rhs) {
if (this.speechBuffer_.length !== rhs.speechBuffer_.length ||
this.brailleBuffer_.length !== rhs.brailleBuffer_.length) {
return false;
}
for (let i = 0; i < this.speechBuffer_.length; i++) {
if (this.speechBuffer_[i].toString() !==
rhs.speechBuffer_[i].toString()) {
return false;
}
}
for (let j = 0; j < this.brailleBuffer_.length; j++) {
if (this.brailleBuffer_[j].toString() !==
rhs.brailleBuffer_[j].toString()) {
return false;
}
}
return true;
}
/** @override */
render(range, prevRange, type, buff, formatLog, optionalArgs = {}) {
if (prevRange && !prevRange.isValid()) {
prevRange = null;
}
// Scan all ancestors to get the value of |contextOrder|.
let parent = range.start.node;
const prevParent = prevRange ? prevRange.start.node : parent;
if (!parent || !prevParent) {
return;
}
while (parent) {
if (parent.role === RoleType.WINDOW) {
break;
}
if (OutputRoleInfo[parent.role] &&
OutputRoleInfo[parent.role].contextOrder) {
this.contextOrder_ =
OutputRoleInfo[parent.role].contextOrder || this.contextOrder_;
break;
}
parent = parent.parent;
}
if (range.isSubNode()) {
this.subNode_(range, prevRange, type, buff, formatLog);
} else {
this.range_(range, prevRange, type, buff, formatLog, optionalArgs);
}
this.hint_(
range, AutomationUtil.getUniqueAncestors(prevParent, range.start.node),
type, buff, formatLog);
}
/**
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @param {!Array<Spannable>} rangeBuff
* @param {!OutputFormatLogger} formatLog
* @param {{suppressStartEndAncestry: (boolean|undefined)}} optionalArgs
* @private
*/
range_(range, prevRange, type, rangeBuff, formatLog, optionalArgs = {}) {
if (!range.start.node || !range.end.node) {
return;
}
if (!prevRange && range.start.node.root) {
prevRange = CursorRange.fromNode(range.start.node.root);
} else if (!prevRange) {
return;
}
const isForward = prevRange.compare(range) === Dir.FORWARD;
const addContextBefore =
this.contextOrder_ === outputTypes.OutputContextOrder.FIRST ||
this.contextOrder_ === outputTypes.OutputContextOrder.FIRST_AND_LAST ||
(this.contextOrder_ === outputTypes.OutputContextOrder.DIRECTED &&
isForward);
const addContextAfter =
this.contextOrder_ === outputTypes.OutputContextOrder.LAST ||
this.contextOrder_ === outputTypes.OutputContextOrder.FIRST_AND_LAST ||
(this.contextOrder_ === outputTypes.OutputContextOrder.DIRECTED &&
!isForward);
const preferStartOrEndAncestry =
this.contextOrder_ === outputTypes.OutputContextOrder.FIRST_AND_LAST;
let prevNode = prevRange.start.node;
let node = range.start.node;
const formatNodeAndAncestors = (node, prevNode) => {
const buff = [];
if (addContextBefore) {
this.ancestry_(
node, prevNode, type, buff, formatLog,
{preferStart: preferStartOrEndAncestry});
}
this.formatNode(node, prevNode, type, buff, formatLog);
if (addContextAfter) {
this.ancestry_(
node, prevNode, type, buff, formatLog,
{preferEnd: preferStartOrEndAncestry});
}
if (node.location) {
this.locations_.push(node.location);
}
return buff;
};
let lca = null;
if (range.start.node !== range.end.node) {
lca = AutomationUtil.getLeastCommonAncestor(
range.end.node, range.start.node);
}
if (addContextAfter) {
prevNode = lca || prevNode;
}
// Do some bookkeeping to see whether this range partially covers node(s) at
// its endpoints.
let hasPartialNodeStart = false;
let hasPartialNodeEnd = false;
if (AutomationPredicate.selectableText(range.start.node) &&
range.start.index > 0) {
hasPartialNodeStart = true;
}
if (AutomationPredicate.selectableText(range.end.node) &&
range.end.index >= 0 && range.end.index < range.end.node.name.length) {
hasPartialNodeEnd = true;
}
let pred;
if (range.isInlineText()) {
pred = AutomationPredicate.leaf;
} else if (hasPartialNodeStart || hasPartialNodeEnd) {
pred = AutomationPredicate.selectableText;
} else {
pred = AutomationPredicate.object;
}
// Computes output for nodes (including partial subnodes) between endpoints
// of |range|.
while (node && range.end.node &&
AutomationUtil.getDirection(node, range.end.node) === Dir.FORWARD) {
if (hasPartialNodeStart && node === range.start.node) {
if (range.start.index !== range.start.node.name.length) {
const partialRange = new CursorRange(
new Cursor(node, range.start.index),
new Cursor(
node, node.name.length, {preferNodeStartEquivalent: true}));
this.subNode_(partialRange, prevRange, type, rangeBuff, formatLog);
}
} else if (hasPartialNodeEnd && node === range.end.node) {
if (range.end.index !== 0) {
const partialRange = new CursorRange(
new Cursor(node, 0), new Cursor(node, range.end.index));
this.subNode_(partialRange, prevRange, type, rangeBuff, formatLog);
}
} else {
rangeBuff.push.apply(rangeBuff, formatNodeAndAncestors(node, prevNode));
}
// End early if the range is just a single node.
if (range.start.node === range.end.node) {
break;
}
prevNode = node;
node = AutomationUtil.findNextNode(
node, Dir.FORWARD, pred, {root: r => r === lca}) ||
prevNode;
// Reached a boundary.
if (node === prevNode) {
break;
}
}
// Finally, add on ancestry announcements, if needed.
if (addContextAfter) {
// No lca; the range was already fully described.
if (lca == null || !prevRange.start.node) {
return;
}
// Since the lca itself needs to be part of the ancestry output, use its
// first child as a target.
const target = lca.firstChild || lca;
this.ancestry_(target, prevRange.start.node, type, rangeBuff, formatLog);
}
}
/**
* @param {!AutomationNode} node
* @param {!AutomationNode} prevNode
* @param {!outputTypes.OutputEventType} type
* @param {!Array<Spannable>} buff
* @param {!OutputFormatLogger} formatLog
* @param {{suppressStartEndAncestry: (boolean|undefined),
* preferStart: (boolean|undefined),
* preferEnd: (boolean|undefined)
* }} optionalArgs
* @private
*/
ancestry_(node, prevNode, type, buff, formatLog, optionalArgs = {}) {
if (!SettingsManager.get('useVerboseMode')) {
return;
}
if (OutputRoleInfo[node.role] && OutputRoleInfo[node.role].ignoreAncestry) {
return;
}
const info = new OutputAncestryInfo(
node, prevNode, Boolean(optionalArgs.suppressStartEndAncestry));
// Enter, leave ancestry.
this.ancestryHelper_({
node,
prevNode,
buff,
formatLog,
type,
ancestors: info.leaveAncestors,
navigationType: outputTypes.OutputNavigationType.LEAVE,
exclude: [...info.enterAncestors, node],
});
this.ancestryHelper_({
node,
prevNode,
buff,
formatLog,
type,
ancestors: info.enterAncestors,
navigationType: outputTypes.OutputNavigationType.ENTER,
excludePreviousAncestors: true,
});
if (optionalArgs.suppressStartEndAncestry) {
return;
}
// Start of, end of ancestry.
if (!optionalArgs.preferEnd) {
this.ancestryHelper_({
node,
prevNode,
buff,
formatLog,
type,
ancestors: info.startAncestors,
navigationType: outputTypes.OutputNavigationType.START_OF,
excludePreviousAncestors: true,
});
}
if (!optionalArgs.preferStart) {
this.ancestryHelper_({
node,
prevNode,
buff,
formatLog,
type,
ancestors: info.endAncestors,
navigationType: outputTypes.OutputNavigationType.END_OF,
exclude: [...info.startAncestors].concat(node),
});
}
}
/**
* @param {{
* node: !AutomationNode,
* prevNode: !AutomationNode,
* type: !outputTypes.OutputEventType,
* buff: !Array<Spannable>,
* formatLog: !OutputFormatLogger,
* ancestors: !Array<!AutomationNode>,
* navigationType: !outputTypes.OutputNavigationType,
* exclude: (!Array<!AutomationNode>|undefined),
* excludePreviousAncestors: (boolean|undefined)
* }} args
* @private
*/
ancestryHelper_(args) {
let {node, prevNode, buff, formatLog, type, ancestors, navigationType} =
args;
const excludeRoles =
args.exclude ? new Set(args.exclude.map(node => node.role)) : new Set();
// Customize for braille node annotations.
const originalBuff = buff;
for (let j = ancestors.length - 1, formatNode; (formatNode = ancestors[j]);
j--) {
const roleInfo = OutputRoleInfo[formatNode.role] || {};
if (!roleInfo.verboseAncestry &&
(excludeRoles.has(formatNode.role) ||
(args.excludePreviousAncestors &&
this.formattedAncestors_.has(formatNode)))) {
continue;
}
const rule = new AncestryOutputRule(
type, formatNode.role, navigationType, this.formatAsBraille);
if (!rule.defined) {
continue;
}
if (this.formatAsBraille) {
buff = /** @type {!Array<Spannable>} */ ([]);
formatLog.bufferClear();
}
excludeRoles.add(formatNode.role);
formatLog.writeRule(rule.specifier);
this.formattedAncestors_.add(formatNode);
OutputFormatter.format(this, {
node: formatNode,
outputFormat: rule.enterFormat,
outputBuffer: buff,
outputFormatLogger: formatLog,
opt_prevNode: prevNode,
});
if (this.formatAsBraille && buff.length) {
const nodeSpan = this.mergeBraille_(buff);
nodeSpan.setSpan(
new outputTypes.OutputNodeSpan(formatNode), 0, nodeSpan.length);
originalBuff.push(nodeSpan);
}
}
}
/**
* @param {!AutomationNode} node
* @param {!AutomationNode} prevNode
* @param {!outputTypes.OutputEventType} type
* @param {!Array<Spannable>} buff
* @param {!OutputFormatLogger} formatLog
* @override
*/
formatNode(node, prevNode, type, buff, formatLog) {
const originalBuff = buff;
if (this.formatOptions_.braille) {
buff = [];
formatLog.bufferClear();
}
const rule = new OutputRule(type);
rule.output = outputTypes.OutputFormatType.SPEAK;
rule.populateRole(node.role, rule.output);
if (this.formatOptions_.braille) {
// Overwrite rule by braille rule if exists.
if (rule.populateRole(node.role, outputTypes.OutputFormatType.BRAILLE)) {
rule.output = outputTypes.OutputFormatType.BRAILLE;
}
}
formatLog.writeRule(rule.specifier);
OutputFormatter.format(this, {
node,
outputFormat: rule.formatString,
outputBuffer: buff,
outputFormatLogger: formatLog,
opt_prevNode: prevNode,
});
// Restore braille and add an annotation for this node.
if (this.formatOptions_.braille) {
const nodeSpan = this.mergeBraille_(buff);
nodeSpan.setSpan(
new outputTypes.OutputNodeSpan(node), 0, nodeSpan.length);
originalBuff.push(nodeSpan);
}
}
/**
* @param {!CursorRange} range
* @param {CursorRange} prevRange
* @param {!outputTypes.OutputEventType} type
* @param {!Array<Spannable>} buff
* @private
*/
subNode_(range, prevRange, type, buff, formatLog) {
if (!prevRange) {
prevRange = range;
}
const dir = CursorRange.getDirection(prevRange, range);
const node = range.start.node;
const prevNode = prevRange.getBound(dir).node;
if (!node || !prevNode) {
return;
}
const options = {annotation: ['name'], isUnique: true};
const rangeStart = range.start.index;
const rangeEnd = range.end.index;
if (this.formatOptions_.braille) {
options.annotation.push(new outputTypes.OutputNodeSpan(node));
const selStart = node.textSelStart;
const selEnd = node.textSelEnd;
if (selStart !== undefined && selEnd >= rangeStart &&
selStart <= rangeEnd) {
// Editable text selection.
// |rangeStart| and |rangeEnd| are indices set by the caller and are
// assumed to be inside of the range. In braille, we only ever expect
// to get ranges surrounding a line as anything smaller doesn't make
// sense.
// |selStart| and |selEnd| reflect the editable selection. The
// relative selStart and relative selEnd for the current line are then
// just the difference between |selStart|, |selEnd| with |rangeStart|.
// See editing_test.js for examples.
options.annotation.push(new outputTypes.OutputSelectionSpan(
selStart - rangeStart, selEnd - rangeStart));
} else if (
rangeStart !== 0 || rangeEnd !== range.start.getText().length) {
// Non-editable text selection over less than the full contents
// covered by the range. We exclude full content underlines because it
// is distracting to read braille with all cells underlined with a
// cursor.
options.annotation.push(
new outputTypes.OutputSelectionSpan(rangeStart, rangeEnd));
}
}
// Intentionally skip subnode output for
// outputTypes.OutputContextOrder.DIRECTED.
if (this.contextOrder_ === outputTypes.OutputContextOrder.FIRST ||
(this.contextOrder_ === outputTypes.OutputContextOrder.FIRST_AND_LAST &&
range.start.index === 0)) {
this.ancestry_(
node, prevNode, type, buff, formatLog, {preferStart: true});