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
|
/* 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/. */
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.sys.mjs",
});
XPCOMUtils.defineLazyServiceGetter(
lazy,
"touchBarUpdater",
"@mozilla.org/widget/touchbarupdater;1",
"nsITouchBarUpdater"
);
// For accessing TouchBarHelper methods from static contexts in this file.
XPCOMUtils.defineLazyServiceGetter(
lazy,
"touchBarHelper",
"@mozilla.org/widget/touchbarhelper;1",
"nsITouchBarHelper"
);
/**
* Executes a XUL command on the top window. Called by the callbacks in each
* TouchBarInput.
*
* @param {string} commandName
* A XUL command.
*/
function execCommand(commandName) {
if (!TouchBarHelper.window) {
return;
}
let command = TouchBarHelper.window.document.getElementById(commandName);
if (command) {
command.doCommand();
}
}
/**
* Static helper function to convert a hexadecimal string to its integer
* value. Used to convert colours to a format accepted by Apple's NSColor code.
*
* @param {string} hexString
* A hexadecimal string, optionally beginning with '#'.
*/
function hexToInt(hexString) {
if (!hexString) {
return null;
}
if (hexString.charAt(0) == "#") {
hexString = hexString.slice(1);
}
let val = parseInt(hexString, 16);
return isNaN(val) ? null : val;
}
const kInputTypes = {
BUTTON: "button",
LABEL: "label",
MAIN_BUTTON: "mainButton",
POPOVER: "popover",
SCROLLVIEW: "scrollView",
SCRUBBER: "scrubber",
};
/**
* An object containing all implemented TouchBarInput objects.
*/
var gBuiltInInputs = {
Back: {
title: "back",
image: "chrome://browser/skin/back.svg",
type: kInputTypes.BUTTON,
callback: () => {
lazy.touchBarHelper.unfocusUrlbar();
execCommand("Browser:Back");
},
},
Forward: {
title: "forward",
image: "chrome://browser/skin/forward.svg",
type: kInputTypes.BUTTON,
callback: () => {
lazy.touchBarHelper.unfocusUrlbar();
execCommand("Browser:Forward");
},
},
Reload: {
title: "reload",
image: "chrome://global/skin/icons/reload.svg",
type: kInputTypes.BUTTON,
callback: () => {
lazy.touchBarHelper.unfocusUrlbar();
execCommand("Browser:Reload");
},
},
Home: {
title: "home",
image: "chrome://browser/skin/home.svg",
type: kInputTypes.BUTTON,
callback: () => {
let win = lazy.BrowserWindowTracker.getTopWindow();
win.BrowserHome();
},
},
Fullscreen: {
title: "fullscreen",
image: "chrome://browser/skin/fullscreen.svg",
type: kInputTypes.BUTTON,
callback: () => execCommand("View:FullScreen"),
},
Find: {
title: "find",
image: "chrome://global/skin/icons/search-glass.svg",
type: kInputTypes.BUTTON,
callback: () => execCommand("cmd_find"),
},
NewTab: {
title: "new-tab",
image: "chrome://global/skin/icons/plus.svg",
type: kInputTypes.BUTTON,
callback: () => execCommand("cmd_newNavigatorTabNoEvent"),
},
Sidebar: {
title: "open-sidebar",
image: "chrome://browser/skin/sidebars.svg",
type: kInputTypes.BUTTON,
callback: () => {
let win = lazy.BrowserWindowTracker.getTopWindow();
win.SidebarUI.toggle();
},
},
AddBookmark: {
title: "add-bookmark",
image: "chrome://browser/skin/bookmark-hollow.svg",
type: kInputTypes.BUTTON,
callback: () => execCommand("Browser:AddBookmarkAs"),
},
ReaderView: {
title: "reader-view",
image: "chrome://browser/skin/reader-mode.svg",
type: kInputTypes.BUTTON,
callback: () => execCommand("View:ReaderView"),
disabled: true, // Updated when the page is found to be Reader View-able.
},
OpenLocation: {
key: "open-location",
title: "open-location",
image: "chrome://global/skin/icons/search-glass.svg",
type: kInputTypes.MAIN_BUTTON,
callback: () => lazy.touchBarHelper.toggleFocusUrlbar(),
},
// This is a special-case `type: kInputTypes.SCRUBBER` element.
// Scrubbers are not yet generally implemented.
// See follow-up bug 1502539.
Share: {
title: "share",
image: "chrome://browser/skin/share.svg",
type: kInputTypes.SCRUBBER,
callback: () => execCommand("cmd_share"),
},
SearchPopover: {
title: "search-popover",
image: "chrome://global/skin/icons/search-glass.svg",
type: kInputTypes.POPOVER,
children: {
SearchScrollViewLabel: {
title: "search-search-in",
type: kInputTypes.LABEL,
},
SearchScrollView: {
key: "search-scrollview",
type: kInputTypes.SCROLLVIEW,
children: {
Bookmarks: {
title: "search-bookmarks",
type: kInputTypes.BUTTON,
callback: () =>
lazy.touchBarHelper.insertRestrictionInUrlbar(
lazy.UrlbarTokenizer.RESTRICT.BOOKMARK
),
},
OpenTabs: {
title: "search-opentabs",
type: kInputTypes.BUTTON,
callback: () =>
lazy.touchBarHelper.insertRestrictionInUrlbar(
lazy.UrlbarTokenizer.RESTRICT.OPENPAGE
),
},
History: {
title: "search-history",
type: kInputTypes.BUTTON,
callback: () =>
lazy.touchBarHelper.insertRestrictionInUrlbar(
lazy.UrlbarTokenizer.RESTRICT.HISTORY
),
},
Tags: {
title: "search-tags",
type: kInputTypes.BUTTON,
callback: () =>
lazy.touchBarHelper.insertRestrictionInUrlbar(
lazy.UrlbarTokenizer.RESTRICT.TAG
),
},
},
},
},
},
};
// We create a new flat object to cache strings. Since gBuiltInInputs is a
// tree, caching/retrieval of localized strings would otherwise require tree
// traversal.
var localizedStrings = {};
const kHelperObservers = new Set([
"bookmark-icon-updated",
"fullscreen-painted",
"reader-mode-available",
"touchbar-location-change",
"quit-application",
"intl:app-locales-changed",
"urlbar-focus",
"urlbar-blur",
]);
/**
* JS-implemented TouchBarHelper class.
* Provides services to the Mac Touch Bar.
*/
export class TouchBarHelper {
constructor() {
for (let topic of kHelperObservers) {
Services.obs.addObserver(this, topic);
}
// We cache our search popover since otherwise it is frequently
// created/destroyed for the urlbar-focus/blur events.
this._searchPopover = this.getTouchBarInput("SearchPopover");
this._inputsNotUpdated = new Set();
}
destructor() {
this._searchPopover = null;
for (let topic of kHelperObservers) {
Services.obs.removeObserver(this, topic);
}
}
get activeTitle() {
if (!TouchBarHelper.window) {
return "";
}
let tabbrowser = TouchBarHelper.window.ownerGlobal.gBrowser;
let activeTitle;
if (tabbrowser) {
activeTitle = tabbrowser.selectedBrowser.contentTitle;
}
return activeTitle;
}
get allItems() {
let layoutItems = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
let window = TouchBarHelper.window;
if (
!window ||
!window.isChromeWindow ||
window.document.documentElement.getAttribute("windowtype") !=
"navigator:browser"
) {
return layoutItems;
}
// Every input must be updated at least once so that all assets (titles,
// icons) are loaded. We keep track of which inputs haven't updated and
// run an update on them ASAP.
this._inputsNotUpdated.clear();
for (let inputName of Object.keys(gBuiltInInputs)) {
let input = this.getTouchBarInput(inputName);
if (!input) {
continue;
}
this._inputsNotUpdated.add(inputName);
layoutItems.appendElement(input);
}
return layoutItems;
}
static get window() {
return lazy.BrowserWindowTracker.getTopWindow();
}
get document() {
if (!TouchBarHelper.window) {
return null;
}
return TouchBarHelper.window.document;
}
get isUrlbarFocused() {
if (!TouchBarHelper.window || !TouchBarHelper.window.gURLBar) {
return false;
}
return TouchBarHelper.window.gURLBar.focused;
}
toggleFocusUrlbar() {
if (this.isUrlbarFocused) {
this.unfocusUrlbar();
} else {
execCommand("Browser:OpenLocation");
}
}
unfocusUrlbar() {
if (!this.isUrlbarFocused) {
return;
}
TouchBarHelper.window.gURLBar.blur();
}
static get baseWindow() {
return TouchBarHelper.window
? TouchBarHelper.window.docShell.treeOwner.QueryInterface(
Ci.nsIBaseWindow
)
: null;
}
getTouchBarInput(inputName) {
if (inputName == "SearchPopover" && this._searchPopover) {
return this._searchPopover;
}
if (!inputName || !gBuiltInInputs.hasOwnProperty(inputName)) {
return null;
}
let inputData = gBuiltInInputs[inputName];
let item = new TouchBarInput(inputData);
// Skip localization if there is already a cached localized title or if
// no title is needed.
if (
!inputData.hasOwnProperty("title") ||
localizedStrings[inputData.title]
) {
return item;
}
// Async l10n fills in the localized input labels after the initial load.
this._l10n.formatValue(inputData.title).then(result => {
item.title = result;
localizedStrings[inputData.title] = result; // Cache result.
// Checking TouchBarHelper.window since this callback can fire after all windows are closed.
if (TouchBarHelper.window) {
if (this._inputsNotUpdated) {
this._inputsNotUpdated.delete(inputName);
}
lazy.touchBarUpdater.updateTouchBarInputs(TouchBarHelper.baseWindow, [
item,
]);
}
});
return item;
}
/**
* Fetches a specific Touch Bar Input by name and updates it on the Touch Bar.
*
* @param {...*} inputNames
* A key/keys to a value/values in the gBuiltInInputs object in this file.
*/
_updateTouchBarInputs(...inputNames) {
if (!TouchBarHelper.window || !inputNames.length) {
return;
}
let inputs = [];
for (let inputName of new Set([...inputNames, ...this._inputsNotUpdated])) {
let input = this.getTouchBarInput(inputName);
if (!input) {
continue;
}
this._inputsNotUpdated.delete(inputName);
inputs.push(input);
}
lazy.touchBarUpdater.updateTouchBarInputs(
TouchBarHelper.baseWindow,
inputs
);
}
/**
* Inserts a restriction token into the Urlbar ahead of the current typed
* search term.
*
* @param {string} restrictionToken
* The restriction token to be inserted into the Urlbar. Preferably
* sourced from UrlbarTokenizer.RESTRICT.
*/
insertRestrictionInUrlbar(restrictionToken) {
if (!TouchBarHelper.window) {
return;
}
let searchString = "";
if (
TouchBarHelper.window.gURLBar.getAttribute("pageproxystate") != "valid"
) {
searchString = TouchBarHelper.window.gURLBar.lastSearchString.trimStart();
if (
Object.values(lazy.UrlbarTokenizer.RESTRICT).includes(searchString[0])
) {
searchString = searchString.substring(1).trimStart();
}
}
TouchBarHelper.window.gURLBar.search(
`${restrictionToken} ${searchString}`,
{ searchModeEntry: "touchbar" }
);
}
observe(subject, topic, data) {
switch (topic) {
case "touchbar-location-change":
let updatedInputs = ["Back", "Forward"];
gBuiltInInputs.Back.disabled =
!TouchBarHelper.window.gBrowser.canGoBack;
gBuiltInInputs.Forward.disabled =
!TouchBarHelper.window.gBrowser.canGoForward;
if (subject.QueryInterface(Ci.nsIWebProgress)?.isTopLevel) {
this.activeUrl = data;
// ReaderView button is disabled on every toplevel location change
// since Reader View must determine if the new page can be Reader
// Viewed.
updatedInputs.push("ReaderView");
gBuiltInInputs.ReaderView.disabled = !data.startsWith("about:reader");
}
this._updateTouchBarInputs(...updatedInputs);
break;
case "fullscreen-painted":
if (TouchBarHelper.window.document.fullscreenElement) {
gBuiltInInputs.OpenLocation.title = "touchbar-fullscreen-exit";
gBuiltInInputs.OpenLocation.image =
"chrome://browser/skin/fullscreen-exit.svg";
gBuiltInInputs.OpenLocation.callback = () => {
TouchBarHelper.window.windowUtils.exitFullscreen();
};
} else {
gBuiltInInputs.OpenLocation.title = "open-location";
gBuiltInInputs.OpenLocation.image =
"chrome://global/skin/icons/search-glass.svg";
gBuiltInInputs.OpenLocation.callback = () =>
execCommand("Browser:OpenLocation", "OpenLocation");
}
this._updateTouchBarInputs("OpenLocation");
break;
case "bookmark-icon-updated":
gBuiltInInputs.AddBookmark.image =
data == "starred"
? "chrome://browser/skin/bookmark.svg"
: "chrome://browser/skin/bookmark-hollow.svg";
this._updateTouchBarInputs("AddBookmark");
break;
case "reader-mode-available":
gBuiltInInputs.ReaderView.disabled = false;
this._updateTouchBarInputs("ReaderView");
break;
case "urlbar-focus":
if (!this._searchPopover) {
this._searchPopover = this.getTouchBarInput("SearchPopover");
}
lazy.touchBarUpdater.showPopover(
TouchBarHelper.baseWindow,
this._searchPopover,
true
);
break;
case "urlbar-blur":
if (!this._searchPopover) {
this._searchPopover = this.getTouchBarInput("SearchPopover");
}
lazy.touchBarUpdater.showPopover(
TouchBarHelper.baseWindow,
this._searchPopover,
false
);
break;
case "intl:app-locales-changed":
this._searchPopover = null;
localizedStrings = {};
// This event can fire before this._l10n updates to switch languages,
// so all the new translations are in the old language. To avoid this,
// we need to reinitialize this._l10n.
this._l10n = new Localization(["browser/touchbar/touchbar.ftl"]);
helperProto._l10n = this._l10n;
this._updateTouchBarInputs(...Object.keys(gBuiltInInputs));
break;
case "quit-application":
this.destructor();
break;
}
}
}
const helperProto = TouchBarHelper.prototype;
helperProto.QueryInterface = ChromeUtils.generateQI(["nsITouchBarHelper"]);
helperProto._l10n = new Localization(["browser/touchbar/touchbar.ftl"]);
/**
* A representation of a Touch Bar input.
*
* @param {object} input
* An object representing a Touch Bar Input.
* Contains listed properties.
* @param {string} input.title
* The lookup key for the button's localized text title.
* @param {string} input.image
* A URL pointing to an SVG internal to Firefox.
* @param {string} input.type
* The type of Touch Bar input represented by the object.
* Must be a value from kInputTypes.
* @param {Function} input.callback
* A callback invoked when a touchbar item is touched.
* @param {string} [input.color]
* A string in hex format specifying the button's background color.
* If omitted, the default background color is used.
* @param {bool} [input.disabled]
* If `true`, the Touch Bar input is greyed out and inoperable.
* @param {Array} [input.children]
* An array of input objects that will be displayed as children of
* this input. Available only for types KInputTypes.POPOVER and
* kInputTypes.SCROLLVIEW.
*/
export class TouchBarInput {
constructor(input) {
this._key = input.key || input.title;
this._title = localizedStrings[input.title] || "";
this._image = input.image;
this._type = input.type;
this._callback = input.callback;
this._color = hexToInt(input.color);
this._disabled = input.hasOwnProperty("disabled") ? input.disabled : false;
if (input.children) {
this._children = [];
let toLocalize = [];
for (let childData of Object.values(input.children)) {
let initializedChild = new TouchBarInput(childData);
if (!initializedChild) {
continue;
}
// Children's types are prepended by the parent's type. This is so we
// can uniquely identify a child input from a standalone input with
// the same name. (e.g. a button called "back" in a popover would be a
// "popover-button.back" vs. a "button.back").
initializedChild.type = input.type + "-" + initializedChild.type;
this._children.push(initializedChild);
// Skip l10n for inputs without a title or those already localized.
if (childData.title && !localizedStrings[childData.title]) {
toLocalize.push(initializedChild);
}
}
this._localizeChildren(toLocalize);
}
}
get key() {
return this._key;
}
get title() {
return this._title;
}
set title(title) {
this._title = title;
}
get image() {
return this._image ? Services.io.newURI(this._image) : null;
}
set image(image) {
this._image = image;
}
get type() {
return this._type == "" ? "button" : this._type;
}
set type(type) {
this._type = type;
}
get callback() {
return this._callback;
}
set callback(callback) {
this._callback = callback;
}
get color() {
return this._color;
}
set color(color) {
this._color = this.hexToInt(color);
}
get disabled() {
return this._disabled || false;
}
set disabled(disabled) {
this._disabled = disabled;
}
get children() {
if (!this._children) {
return null;
}
let children = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
for (let child of this._children) {
children.appendElement(child);
}
return children;
}
/**
* Apply Fluent l10n to child inputs.
*
* @param {Array} children
* An array of initialized TouchBarInputs.
*/
async _localizeChildren(children) {
if (!children || !children.length) {
return;
}
let titles = await helperProto._l10n.formatValues(
children.map(child => ({ id: child.key }))
);
// In the TouchBarInput constuctor, we filtered so children contains only
// those inputs with titles to be localized. We can be confident that the
// results in titles match up with the inputs to be localized.
children.forEach(function (child, index) {
child.title = titles[index];
localizedStrings[child.key] = child.title;
});
lazy.touchBarUpdater.updateTouchBarInputs(
TouchBarHelper.baseWindow,
children
);
}
}
TouchBarInput.prototype.QueryInterface = ChromeUtils.generateQI([
"nsITouchBarInput",
]);
|