summaryrefslogtreecommitdiffstats
path: root/comm/mail/base/content/specialTabs.js
blob: 15a163c9815674879e6bdfa413899f0e52209750 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
/* 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/. */

/* global MozElements, openOptionsDialog */

/* import-globals-from utilityOverlay.js */

/* globals ZoomManager */ // From viewZoomOverlay.js
/* globals PrintUtils */ // From printUtils.js

var { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);
var { AddonManager } = ChromeUtils.importESModule(
  "resource://gre/modules/AddonManager.sys.mjs"
);
var { ExtensionParent } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionParent.sys.mjs"
);
var { MailE10SUtils } = ChromeUtils.import(
  "resource:///modules/MailE10SUtils.jsm"
);

function tabProgressListener(aTab, aStartsBlank) {
  this.mTab = aTab;
  this.mBrowser = aTab.browser;
  this.mBlank = aStartsBlank;
  this.mProgressListener = null;
}

tabProgressListener.prototype = {
  mTab: null,
  mBrowser: null,
  mBlank: null,
  mProgressListener: null,

  // cache flags for correct status bar update after tab switching
  mStateFlags: 0,
  mStatus: 0,
  mMessage: "",

  // count of open requests (should always be 0 or 1)
  mRequestCount: 0,

  addProgressListener(aProgressListener) {
    this.mProgressListener = aProgressListener;
  },

  onProgressChange(
    aWebProgress,
    aRequest,
    aCurSelfProgress,
    aMaxSelfProgress,
    aCurTotalProgress,
    aMaxTotalProgress
  ) {
    if (this.mProgressListener) {
      this.mProgressListener.onProgressChange(
        aWebProgress,
        aRequest,
        aCurSelfProgress,
        aMaxSelfProgress,
        aCurTotalProgress,
        aMaxTotalProgress
      );
    }
  },
  onProgressChange64(
    aWebProgress,
    aRequest,
    aCurSelfProgress,
    aMaxSelfProgress,
    aCurTotalProgress,
    aMaxTotalProgress
  ) {
    if (this.mProgressListener) {
      this.mProgressListener.onProgressChange64(
        aWebProgress,
        aRequest,
        aCurSelfProgress,
        aMaxSelfProgress,
        aCurTotalProgress,
        aMaxTotalProgress
      );
    }
  },
  onLocationChange(aWebProgress, aRequest, aLocationURI, aFlags) {
    if (this.mProgressListener) {
      this.mProgressListener.onLocationChange(
        aWebProgress,
        aRequest,
        aLocationURI,
        aFlags
      );
    }
    // onLocationChange is called for both the top-level content
    // and the subframes.
    if (aWebProgress.isTopLevel) {
      // Don't clear the favicon if this onLocationChange was triggered
      // by a pushState or a replaceState. See bug 550565.
      if (
        aWebProgress.isLoadingDocument &&
        !(aWebProgress.loadType & Ci.nsIDocShell.LOAD_CMD_PUSHSTATE) &&
        !(aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT)
      ) {
        this.mTab.favIconUrl = null;
      }

      var location = aLocationURI ? aLocationURI.spec : "";
      if (aLocationURI && !aLocationURI.schemeIs("about")) {
        this.mTab.backButton.disabled = !this.mBrowser.canGoBack;
        this.mTab.forwardButton.disabled = !this.mBrowser.canGoForward;
        this.mTab.urlbar.value = location;
        this.mTab.root.removeAttribute("collapsed");
      } else {
        this.mTab.root.setAttribute("collapsed", "false");
      }

      // Although we're unlikely to be loading about:blank, we'll check it
      // anyway just in case. The second condition is for new tabs, otherwise
      // the reload function is enabled until tab is refreshed.
      this.mTab.reloadEnabled = !(
        (location == "about:blank" && !this.mBrowser.browsingContext.opener) ||
        location == ""
      );
    }
  },
  onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) {
    if (this.mProgressListener) {
      this.mProgressListener.onStateChange(
        aWebProgress,
        aRequest,
        aStateFlags,
        aStatus
      );
    }

    if (!aRequest) {
      return;
    }

    let tabmail = document.getElementById("tabmail");

    if (aStateFlags & Ci.nsIWebProgressListener.STATE_START) {
      this.mRequestCount++;
    } else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
      // Since we (try to) only handle STATE_STOP of the last request,
      // the count of open requests should now be 0.
      this.mRequestCount = 0;
    }

    if (
      aStateFlags & Ci.nsIWebProgressListener.STATE_START &&
      aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK
    ) {
      if (!this.mBlank) {
        this.mTab.title = specialTabs.contentTabType.loadingTabString;
        this.mTab.securityIcon.setLoading(true);
        tabmail.setTabBusy(this.mTab, true);
        tabmail.setTabTitle(this.mTab);
      }

      // Set our unit testing variables accordingly
      this.mTab.pageLoading = true;
      this.mTab.pageLoaded = false;
    } else if (
      aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
      aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK
    ) {
      this.mBlank = false;
      this.mTab.securityIcon.setLoading(false);
      tabmail.setTabBusy(this.mTab, false);
      this.mTab.title = this.mTab.browser.contentTitle;
      tabmail.setTabTitle(this.mTab);

      // Set our unit testing variables accordingly
      this.mTab.pageLoading = false;
      this.mTab.pageLoaded = true;

      // If we've finished loading, and we've not had an icon loaded from a
      // link element, then we try using the default icon for the site.
      if (aWebProgress.isTopLevel && !this.mTab.favIconUrl) {
        specialTabs.useDefaultFavIcon(this.mTab);
      }
    }
  },
  onStatusChange(aWebProgress, aRequest, aStatus, aMessage) {
    if (this.mProgressListener) {
      this.mProgressListener.onStatusChange(
        aWebProgress,
        aRequest,
        aStatus,
        aMessage
      );
    }
  },
  onSecurityChange(aWebProgress, aRequest, aState) {
    if (this.mProgressListener) {
      this.mProgressListener.onSecurityChange(aWebProgress, aRequest, aState);
    }

    const wpl = Ci.nsIWebProgressListener;
    const wpl_security_bits =
      wpl.STATE_IS_SECURE | wpl.STATE_IS_BROKEN | wpl.STATE_IS_INSECURE;
    let level = "";
    switch (aState & wpl_security_bits) {
      case wpl.STATE_IS_SECURE:
        level = "high";
        break;
      case wpl.STATE_IS_BROKEN:
        level = "broken";
        break;
    }
    this.mTab.securityIcon.setSecurityLevel(level);
  },
  onContentBlockingEvent(aWebProgress, aRequest, aEvent) {
    if (this.mProgressListener) {
      this.mProgressListener.onContentBlockingEvent(
        aWebProgress,
        aRequest,
        aEvent
      );
    }
  },
  onRefreshAttempted(aWebProgress, aURI, aDelay, aSameURI) {
    if (this.mProgressListener) {
      return this.mProgressListener.onRefreshAttempted(
        aWebProgress,
        aURI,
        aDelay,
        aSameURI
      );
    }
    return true;
  },
  QueryInterface: ChromeUtils.generateQI([
    "nsIWebProgressListener",
    "nsIWebProgressListener2",
    "nsISupportsWeakReference",
  ]),
};

/**
 * Handles tab icons for parent process browsers. The DOMLinkAdded event won't
 * fire for child process browsers, that is handled by LinkHandlerParent.
 */
var DOMLinkHandler = {
  handleEvent(event) {
    switch (event.type) {
      case "DOMLinkAdded":
      case "DOMLinkChanged":
        this.onLinkAdded(event);
        break;
    }
  },
  onLinkAdded(event) {
    let link = event.target;
    let rel = link.rel && link.rel.toLowerCase();
    if (!link || !link.ownerDocument || !rel || !link.href) {
      return;
    }

    if (rel.split(/\s+/).includes("icon")) {
      if (!Services.prefs.getBoolPref("browser.chrome.site_icons")) {
        return;
      }

      let targetDoc = link.ownerDocument;

      let uri = Services.io.newURI(link.href, targetDoc.characterSet);

      // Verify that the load of this icon is legal.
      // Some error or special pages can load their favicon.
      // To be on the safe side, only allow chrome:// favicons.
      let isAllowedPage =
        targetDoc.documentURI == "about:home" ||
        ["about:neterror?", "about:blocked?", "about:certerror?"].some(
          function (aStart) {
            targetDoc.documentURI.startsWith(aStart);
          }
        );

      if (!isAllowedPage || !uri.schemeIs("chrome")) {
        // Be extra paraniod and just make sure we're not going to load
        // something we shouldn't. Firefox does this, so we're doing the same.
        try {
          Services.scriptSecurityManager.checkLoadURIWithPrincipal(
            targetDoc.nodePrincipal,
            uri,
            Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT
          );
        } catch (ex) {
          return;
        }
      }

      try {
        var contentPolicy = Cc[
          "@mozilla.org/layout/content-policy;1"
        ].getService(Ci.nsIContentPolicy);
      } catch (e) {
        // Refuse to load if we can't do a security check.
        return;
      }

      // Security says okay, now ask content policy. This is probably trying to
      // ensure that the image loaded always obeys the content policy. There
      // may have been a chance that it was cached and we're trying to load it
      // direct from the cache and not the normal route.
      let { NetUtil } = ChromeUtils.import(
        "resource://gre/modules/NetUtil.jsm"
      );
      let tmpChannel = NetUtil.newChannel({
        uri,
        loadingNode: targetDoc,
        securityFlags: Ci.nsILoadInfo.SEC_ONLY_FOR_EXPLICIT_CONTENTSEC_CHECK,
        contentPolicyType: Ci.nsIContentPolicy.TYPE_IMAGE,
      });
      let tmpLoadInfo = tmpChannel.loadInfo;
      if (
        contentPolicy.shouldLoad(uri, tmpLoadInfo, link.type) !=
        Ci.nsIContentPolicy.ACCEPT
      ) {
        return;
      }

      let tab = document
        .getElementById("tabmail")
        .getBrowserForDocument(targetDoc.defaultView);

      // If we don't have a browser/tab, then don't load the icon.
      if (!tab) {
        return;
      }

      // Just set the url on the browser and we'll display the actual icon
      // when we finish loading the page.
      specialTabs.setFavIcon(tab, link.href);
    }
  },
};

var contentTabBaseType = {
  // List of URLs that will receive special treatment when opened in a tab.
  // Note that about:preferences is loaded via a different mechanism.
  inContentWhitelist: [
    "about:addons",
    "about:addressbook",
    "about:blank",
    "about:profiles",
    "about:*",
  ],

  // Code to run if a particular document is loaded in a tab.
  // The array members (functions) are for the respective document URLs
  // as specified in inContentWhitelist.
  inContentOverlays: [
    // about:addons
    function (aDocument, aTab) {
      Services.scriptloader.loadSubScript(
        "chrome://messenger/content/aboutAddonsExtra.js",
        aDocument.defaultView
      );
    },

    // about:addressbook provides its own context menu.
    function (aDocument, aTab) {
      aTab.browser.removeAttribute("context");
    },

    // Let's not mess with about:blank.
    null,

    // about:profiles
    function (aDocument, aTab) {
      let win = aDocument.defaultView;
      // Need a timeout to let the script run to create the needed buttons.
      win.setTimeout(() => {
        win.MozXULElement.insertFTLIfNeeded("messenger/aboutProfilesExtra.ftl");
        for (let button of aDocument.querySelectorAll(
          `[data-l10n-id="profiles-launch-profile"]`
        )) {
          win.document.l10n.setAttributes(
            button,
            "profiles-launch-profile-plain"
          );
        }
      }, 500);
    },

    // Other about:* pages.
    function (aDocument, aTab) {
      // Provide context menu for about:* pages.
      aTab.browser.setAttribute("context", "aboutPagesContext");
    },
  ],

  shouldSwitchTo({ url, duplicate }) {
    if (duplicate) {
      return -1;
    }

    let tabmail = document.getElementById("tabmail");
    let tabInfo = tabmail.tabInfo;
    let uri;

    try {
      uri = Services.io.newURI(url);
    } catch (ex) {
      return -1;
    }

    for (
      let selectedIndex = 0;
      selectedIndex < tabInfo.length;
      ++selectedIndex
    ) {
      // Reuse the same tab, if only the anchors differ - especially for the
      // about: pages, we just want to re-use the same tab.
      if (
        tabInfo[selectedIndex].mode.name == this.name &&
        tabInfo[selectedIndex].browser.currentURI?.specIgnoringRef ==
          uri.specIgnoringRef
      ) {
        // Go to the correct location on the page, but only if it's not the
        // current location. This should NOT cause the page to reload.
        if (tabInfo[selectedIndex].browser.currentURI.spec != uri.spec) {
          MailE10SUtils.loadURI(tabInfo[selectedIndex].browser, uri.spec);
        }
        return selectedIndex;
      }
    }
    return -1;
  },

  closeTab(aTab) {
    aTab.browser.removeEventListener(
      "pagetitlechanged",
      aTab.titleListener,
      true
    );
    aTab.browser.removeEventListener(
      "DOMWindowClose",
      aTab.closeListener,
      true
    );
    aTab.browser.removeEventListener("DOMLinkAdded", DOMLinkHandler);
    aTab.browser.removeEventListener("DOMLinkChanged", DOMLinkHandler);
    aTab.browser.webProgress.removeProgressListener(aTab.filter);
    aTab.filter.removeProgressListener(aTab.progressListener);
    aTab.browser.destroy();
  },

  saveTabState(aTab) {
    aTab.browser.setAttribute("type", "content");
    aTab.browser.removeAttribute("primary");
  },

  showTab(aTab) {
    aTab.browser.setAttribute("type", "content");
    aTab.browser.setAttribute("primary", "true");
    if (aTab.browser.currentURI.spec.startsWith("about:preferences")) {
      aTab.browser.contentDocument.documentElement.focus();
    }
  },

  getBrowser(aTab) {
    return aTab.browser;
  },

  _setUpLoadListener(aTab) {
    let self = this;

    function onLoad(aEvent) {
      let doc = aEvent.target;
      let url = doc.defaultView.location.href;

      // If this document has an overlay defined, run it now.
      let ind = self.inContentWhitelist.indexOf(url);
      if (ind < 0) {
        // Try a wildcard.
        ind = self.inContentWhitelist.indexOf(url.replace(/:.*/, ":*"));
      }
      if (ind >= 0) {
        let overlayFunction = self.inContentOverlays[ind];
        if (overlayFunction) {
          overlayFunction(doc, aTab);
        }
      }
    }

    aTab.loadListener = onLoad;
    aTab.browser.addEventListener("load", aTab.loadListener, true);
  },

  // Internal function used to set up the title listener on a content tab.
  _setUpTitleListener(aTab) {
    function onDOMTitleChanged(aEvent) {
      aTab.title = aTab.browser.contentTitle;
      document.getElementById("tabmail").setTabTitle(aTab);
    }
    // Save the function we'll use as listener so we can remove it later.
    aTab.titleListener = onDOMTitleChanged;
    // Add the listener.
    aTab.browser.addEventListener("pagetitlechanged", aTab.titleListener, true);
  },

  /**
   * Internal function used to set up the close window listener on a content
   * tab.
   */
  _setUpCloseWindowListener(aTab) {
    function onDOMWindowClose(aEvent) {
      if (!aEvent.isTrusted) {
        return;
      }

      // Redirect any window.close events to closing the tab. As a 3-pane tab
      // must be open, we don't need to worry about being the last tab open.
      document.getElementById("tabmail").closeTab(aTab);
      aEvent.preventDefault();
    }
    // Save the function we'll use as listener so we can remove it later.
    aTab.closeListener = onDOMWindowClose;
    // Add the listener.
    aTab.browser.addEventListener("DOMWindowClose", aTab.closeListener, true);
  },

  supportsCommand(aCommand, aTab) {
    switch (aCommand) {
      case "cmd_fullZoomReduce":
      case "cmd_fullZoomEnlarge":
      case "cmd_fullZoomReset":
      case "cmd_fullZoomToggle":
      case "cmd_find":
      case "cmd_findAgain":
      case "cmd_findPrevious":
      case "cmd_print":
      case "button_print":
      case "cmd_stop":
      case "cmd_reload":
      case "Browser:Back":
      case "Browser:Forward":
        return true;
      default:
        return false;
    }
  },

  isCommandEnabled(aCommand, aTab) {
    switch (aCommand) {
      case "cmd_fullZoomReduce":
      case "cmd_fullZoomEnlarge":
      case "cmd_fullZoomReset":
      case "cmd_fullZoomToggle":
      case "cmd_find":
      case "cmd_findAgain":
      case "cmd_findPrevious":
        return true;
      case "cmd_print":
      case "button_print": {
        let uri = aTab.browser?.currentURI;
        if (!uri || !uri.schemeIs("about")) {
          return true;
        }
        return [
          "addressbook",
          "certificate",
          "crashes",
          "credits",
          "license",
          "profiles",
          "support",
          "telemetry",
        ].includes(uri.filePath);
      }
      case "cmd_reload":
        return aTab.reloadEnabled;
      case "cmd_stop":
        return aTab.busy;
      case "Browser:Back":
        return aTab.browser?.canGoBack;
      case "Browser:Forward":
        return aTab.browser?.canGoForward;
      default:
        return false;
    }
  },

  doCommand(aCommand, aTab) {
    switch (aCommand) {
      case "cmd_fullZoomReduce":
        ZoomManager.reduce();
        break;
      case "cmd_fullZoomEnlarge":
        ZoomManager.enlarge();
        break;
      case "cmd_fullZoomReset":
        ZoomManager.reset();
        break;
      case "cmd_fullZoomToggle":
        ZoomManager.toggleZoom();
        break;
      case "cmd_find":
        aTab.findbar.onFindCommand();
        break;
      case "cmd_findAgain":
        aTab.findbar.onFindAgainCommand(false);
        break;
      case "cmd_findPrevious":
        aTab.findbar.onFindAgainCommand(true);
        break;
      case "cmd_print":
        PrintUtils.startPrintWindow(this.getBrowser(aTab).browsingContext, {});
        break;
      case "cmd_stop":
        aTab.browser.stop();
        break;
      case "cmd_reload":
        aTab.browser.reload();
        break;
      case "Browser:Back":
        specialTabs.browserBack();
        break;
      case "Browser:Forward":
        specialTabs.browserForward();
        break;
    }
  },
};

/**
 * Class that wraps the content page loading/security icon.
 */
// Ideally, this could be moved into a sub-class for content tabs.
class SecurityIcon {
  constructor(icon) {
    this.icon = icon;
    this.loading = false;
    this.securityLevel = "";
    this.updateIcon();
  }

  /**
   * Set whether the page is loading.
   *
   * @param {boolean} loading - Whether the page is loading.
   */
  setLoading(loading) {
    if (this.loading !== loading) {
      this.loading = loading;
      this.updateIcon();
    }
  }

  /**
   * Set the security level of the page.
   *
   * @param {"high"|"broken"|""} - The security level for the page, or empty if
   *   it is to be ignored.
   */
  setSecurityLevel(securityLevel) {
    if (this.securityLevel !== securityLevel) {
      this.securityLevel = securityLevel;
      this.updateIcon();
    }
  }

  updateIcon() {
    let src;
    let srcSet;
    let l10nId;
    let secure = false;
    if (this.loading) {
      src = "chrome://global/skin/icons/loading.png";
      srcSet = "chrome://global/skin/icons/loading@2x.png 2x";
      l10nId = "content-tab-page-loading-icon";
    } else {
      switch (this.securityLevel) {
        case "high":
          secure = true;
          src = "chrome://messenger/skin/icons/connection-secure.svg";
          l10nId = "content-tab-security-high-icon";
          break;
        case "broken":
          src = "chrome://messenger/skin/icons/connection-insecure.svg";
          l10nId = "content-tab-security-broken-icon";
          break;
      }
    }
    if (srcSet) {
      this.icon.setAttribute("srcset", srcSet);
    } else {
      this.icon.removeAttribute("srcset");
    }
    if (src) {
      this.icon.setAttribute("src", src);
      // Set alt.
      document.l10n.setAttributes(this.icon, l10nId);
    } else {
      this.icon.removeAttribute("src");
      this.icon.removeAttribute("data-l10n-id");
      this.icon.removeAttribute("alt");
    }
    this.icon.classList.toggle("secure-connection-icon", secure);
  }
}

var specialTabs = {
  _kAboutRightsVersion: 1,
  get _protocolSvc() {
    delete this._protocolSvc;
    return (this._protocolSvc = Cc[
      "@mozilla.org/uriloader/external-protocol-service;1"
    ].getService(Ci.nsIExternalProtocolService));
  },

  get msgNotificationBar() {
    if (!this._notificationBox) {
      this._notificationBox = new MozElements.NotificationBox(element => {
        element.setAttribute("notificationside", "bottom");
        document
          .getElementById("messenger-notification-bottom")
          .append(element);
      });
    }
    return this._notificationBox;
  },

  // This will open any special tabs if necessary on startup.
  openSpecialTabsOnStartup() {
    let tabmail = document.getElementById("tabmail");

    tabmail.registerTabType(this.contentTabType);

    this.showWhatsNewPage();

    // Show the about rights notification if we need to.
    if (this.shouldShowAboutRightsNotification()) {
      this.showAboutRightsNotification();
    }
    if (this.shouldShowPolicyNotification()) {
      // Do it on a timeout to workaround that open in background do not work when called too early.
      setTimeout(this.showPolicyNotification, 10000);
    }
  },

  /**
   * A tab to show content pages.
   */
  contentTabType: {
    __proto__: contentTabBaseType,
    name: "contentTab",
    perTabPanel: "vbox",
    lastBrowserId: 0,
    get loadingTabString() {
      delete this.loadingTabString;
      return (this.loadingTabString = document
        .getElementById("bundle_messenger")
        .getString("loadingTab"));
    },

    modes: {
      contentTab: {
        type: "contentTab",
      },
    },

    /**
     * This is the internal function used by content tabs to open a new tab. To
     * open a contentTab, use specialTabs.openTab("contentTab", aArgs)
     *
     * @param {object} aArgs - The options that content tabs accept.
     * @param {string} aArgs.url - The URL that is to be opened
     * @param {nsIOpenWindowInfo} [aArgs.openWindowInfo] - The opener window
     * @param {"single-site"|"single-page"|null} [aArgs.linkHandler="single-site"]
     *     Restricts navigation in the browser to be opened:
     *     - "single-site" allows only URLs in the same domain as
     *     aArgs.url (including subdomains).
     *     - "single-page" allows only URLs matching aArgs.url.
     *     - `null` applies no such restrictions.
     *     All other links are sent to an external browser.
     * @param {Function} [aArgs.onLoad] - A function that takes an Event and a
     *     DOMNode. It is called when the content page is done loading. The
     *     first argument is the load event, and the second argument is the
     *     xul:browser that holds the page. You can access the inner tab's
     *     window object by accessing the second parameter's contentWindow
     *     property.
     */
    openTab(aTab, aArgs) {
      if (!("url" in aArgs)) {
        throw new Error("url must be specified");
      }

      // First clone the page and set up the basics.
      let clone = document
        .getElementById("contentTab")
        .firstElementChild.cloneNode(true);

      clone.setAttribute("id", "contentTab" + this.lastBrowserId);
      clone.setAttribute("collapsed", false);

      let toolbox = clone.firstElementChild;
      toolbox.setAttribute("id", "contentTabToolbox" + this.lastBrowserId);
      toolbox.firstElementChild.setAttribute(
        "id",
        "contentTabToolbar" + this.lastBrowserId
      );

      aTab.linkedBrowser = aTab.browser = document.createXULElement("browser");
      aTab.browser.setAttribute("id", "contentTabBrowser" + this.lastBrowserId);
      aTab.browser.setAttribute("type", "content");
      aTab.browser.setAttribute("flex", "1");
      aTab.browser.setAttribute("autocompletepopup", "PopupAutoComplete");
      aTab.browser.setAttribute("context", "browserContext");
      aTab.browser.setAttribute("maychangeremoteness", "true");
      aTab.browser.setAttribute("onclick", "return contentAreaClick(event);");
      aTab.browser.openWindowInfo = aArgs.openWindowInfo || null;
      clone.querySelector("stack").appendChild(aTab.browser);

      if (aArgs.skipLoad) {
        clone.querySelector("browser").setAttribute("nodefaultsrc", "true");
      }
      if (aArgs.userContextId) {
        aTab.browser.setAttribute("usercontextid", aArgs.userContextId);
      }
      aTab.panel.setAttribute("id", "contentTabWrapper" + this.lastBrowserId);
      aTab.panel.appendChild(clone);
      aTab.root = clone;

      ExtensionParent.apiManager.emit(
        "extension-browser-inserted",
        aTab.browser
      );

      // For pdf.js use the aboutPagesContext context menu.
      if (aArgs.url.includes("type=application/pdf")) {
        aTab.browser.setAttribute("context", "aboutPagesContext");
      }

      // Start setting up the browser.
      aTab.toolbar = aTab.panel.querySelector(".contentTabToolbar");
      aTab.backButton = aTab.toolbar.querySelector(".back-btn");
      aTab.backButton.addEventListener("command", () => aTab.browser.goBack());
      aTab.forwardButton = aTab.toolbar.querySelector(".forward-btn");
      aTab.forwardButton.addEventListener("command", () =>
        aTab.browser.goForward()
      );
      aTab.securityIcon = new SecurityIcon(
        aTab.toolbar.querySelector(".contentTabSecurity")
      );
      aTab.urlbar = aTab.toolbar.querySelector(".contentTabUrlInput");
      aTab.urlbar.value = aArgs.url;

      // As we're opening this tab, showTab may not get called, so set
      // the type according to if we're opening in background or not.
      let background = "background" in aArgs && aArgs.background;
      if (background) {
        aTab.browser.removeAttribute("primary");
      } else {
        aTab.browser.setAttribute("primary", "true");
      }

      if (aArgs.linkHandler == "single-page") {
        aTab.browser.setAttribute("messagemanagergroup", "single-page");
      } else if (aArgs.linkHandler === null) {
        aTab.browser.setAttribute("messagemanagergroup", "browsers");
      } else {
        aTab.browser.setAttribute("messagemanagergroup", "single-site");
      }

      aTab.browser.addEventListener("DOMLinkAdded", DOMLinkHandler);
      aTab.browser.addEventListener("DOMLinkChanged", DOMLinkHandler);

      // Now initialise the find bar.
      aTab.findbar = document.createXULElement("findbar");
      aTab.findbar.setAttribute(
        "browserid",
        "contentTabBrowser" + this.lastBrowserId
      );
      clone.appendChild(aTab.findbar);

      // Default to reload being disabled.
      aTab.reloadEnabled = false;

      // Now set up the listeners.
      this._setUpLoadListener(aTab);
      this._setUpTitleListener(aTab);
      this._setUpCloseWindowListener(aTab);

      /**
       * Override the browser custom element's version, which returns gBrowser.
       */
      aTab.browser.getTabBrowser = function () {
        return document.getElementById("tabmail");
      };

      if ("onLoad" in aArgs) {
        aTab.browser.addEventListener(
          "load",
          function _contentTab_onLoad(event) {
            aArgs.onLoad(event, aTab.browser);
            aTab.browser.removeEventListener("load", _contentTab_onLoad, true);
          },
          true
        );
      }

      // Create a filter and hook it up to our browser
      let filter = Cc[
        "@mozilla.org/appshell/component/browser-status-filter;1"
      ].createInstance(Ci.nsIWebProgress);
      aTab.filter = filter;
      aTab.browser.webProgress.addProgressListener(
        filter,
        Ci.nsIWebProgress.NOTIFY_ALL
      );

      // Wire up a progress listener to the filter for this browser
      aTab.progressListener = new tabProgressListener(aTab, false);

      filter.addProgressListener(
        aTab.progressListener,
        Ci.nsIWebProgress.NOTIFY_ALL
      );

      if ("onListener" in aArgs) {
        aArgs.onListener(aTab.browser, aTab.progressListener);
      }

      // Initialize our unit testing variables.
      aTab.pageLoading = false;
      aTab.pageLoaded = false;

      // Now start loading the content.
      aTab.title = this.loadingTabString;

      if (!aArgs.skipLoad) {
        MailE10SUtils.loadURI(aTab.browser, aArgs.url, {
          csp: aArgs.csp,
          referrerInfo: aArgs.referrerInfo,
          triggeringPrincipal: aArgs.triggeringPrincipal,
        });
      }

      this.lastBrowserId++;
    },
    tryCloseTab(aTab) {
      return aTab.browser.permitUnload();
    },
    persistTab(aTab) {
      if (aTab.browser.currentURI.spec == "about:blank") {
        return null;
      }

      // Extension pages of temporarily installed extensions cannot be restored.
      if (
        aTab.browser.currentURI.scheme == "moz-extension" &&
        WebExtensionPolicy.getByHostname(aTab.browser.currentURI.host)
          ?.temporarilyInstalled
      ) {
        return null;
      }

      return {
        tabURI: aTab.browser.currentURI.spec,
        linkHandler: aTab.browser.getAttribute("messagemanagergroup"),
        userContextId: `${
          aTab.browser.getAttribute("usercontextid") ||
          Ci.nsIScriptSecurityManager.DEFAULT_USER_CONTEXT_ID
        }`,
      };
    },
    restoreTab(aTabmail, aPersistedState) {
      let tab = aTabmail.openTab("contentTab", {
        background: true,
        duplicate: aPersistedState.duplicate,
        linkHandler: aPersistedState.linkHandler,
        url: aPersistedState.tabURI,
        userContextId: aPersistedState.userContextId,
      });

      if (aPersistedState.tabURI == "about:addons") {
        // Also in `openAddonsMgr` in mailCore.js.
        tab.browser.droppedLinkHandler = event =>
          tab.browser.contentWindow.gDragDrop.onDrop(event);
      }
    },
  },

  /**
   * Shows the what's new page in the system browser if we should.
   * Will update the mstone pref to a new version if needed.
   *
   * @see {BrowserContentHandler.needHomepageOverride}
   */
  showWhatsNewPage() {
    let old_mstone = Services.prefs.getCharPref(
      "mailnews.start_page_override.mstone",
      ""
    );

    let mstone = Services.appinfo.version;
    if (mstone != old_mstone) {
      Services.prefs.setCharPref("mailnews.start_page_override.mstone", mstone);
    }

    if (AppConstants.MOZ_UPDATER) {
      let update = Cc["@mozilla.org/updates/update-manager;1"].getService(
        Ci.nsIUpdateManager
      ).readyUpdate;

      if (update && Services.vc.compare(update.appVersion, old_mstone) > 0) {
        let overridePage = Services.urlFormatter.formatURLPref(
          "mailnews.start_page.override_url"
        );
        overridePage = this.getPostUpdateOverridePage(update, overridePage);
        overridePage = overridePage.replace("%OLD_VERSION%", old_mstone);
        if (overridePage) {
          openLinkExternally(overridePage);
        }
      }
    }
  },

  /**
   * Gets the override page for the first run after the application has been
   * updated.
   *
   * @param {nsIUpdate} update - The nsIUpdate for the update that has been applied.
   * @param {string} defaultOverridePage - The default override page.
   * @returns {string} The override page.
   */
  getPostUpdateOverridePage(update, defaultOverridePage) {
    update = update.QueryInterface(Ci.nsIWritablePropertyBag);
    let actions = update.getProperty("actions");
    // When the update doesn't specify actions fallback to the original behavior
    // of displaying the default override page.
    if (!actions) {
      return defaultOverridePage;
    }

    // The existence of silent or the non-existence of showURL in the actions both
    // mean that an override page should not be displayed.
    if (actions.includes("silent") || !actions.includes("showURL")) {
      return "";
    }

    // If a policy was set to not allow the update.xml-provided
    // URL to be used, use the default fallback (which will also
    // be provided by the policy).
    if (!Services.policies.isAllowed("postUpdateCustomPage")) {
      return defaultOverridePage;
    }

    return update.getProperty("openURL") || defaultOverridePage;
  },

  /**
   * Looks at the existing prefs and determines if we should show the policy or not.
   */
  shouldShowPolicyNotification() {
    let dataSubmissionEnabled = Services.prefs.getBoolPref(
      "datareporting.policy.dataSubmissionEnabled",
      true
    );
    let dataSubmissionPolicyBypassNotification = Services.prefs.getBoolPref(
      "datareporting.policy.dataSubmissionPolicyBypassNotification",
      false
    );
    let dataSubmissionPolicyAcceptedVersion = Services.prefs.getIntPref(
      "datareporting.policy.dataSubmissionPolicyAcceptedVersion",
      0
    );
    let currentPolicyVersion = Services.prefs.getIntPref(
      "datareporting.policy.currentPolicyVersion",
      1
    );
    if (
      !AppConstants.MOZ_DATA_REPORTING ||
      !dataSubmissionEnabled ||
      dataSubmissionPolicyBypassNotification
    ) {
      return false;
    }
    if (dataSubmissionPolicyAcceptedVersion >= currentPolicyVersion) {
      return false;
    }
    return true;
  },

  showPolicyNotification() {
    try {
      let firstRunURL = Services.prefs.getStringPref(
        "datareporting.policy.firstRunURL"
      );
      document.getElementById("tabmail").openTab("contentTab", {
        background: true,
        url: firstRunURL,
      });
    } catch (e) {
      // Show the infobar if it fails to show the privacy policy in the new tab.
      this.showTelemetryNotification();
    }
    let currentPolicyVersion = Services.prefs.getIntPref(
      "datareporting.policy.currentPolicyVersion",
      1
    );
    Services.prefs.setIntPref(
      "datareporting.policy.dataSubmissionPolicyAcceptedVersion",
      currentPolicyVersion
    );
    Services.prefs.setStringPref(
      "datareporting.policy.dataSubmissionPolicyNotifiedTime",
      new Date().getTime().toString()
    );
  },

  showTelemetryNotification() {
    let brandBundle = Services.strings.createBundle(
      "chrome://branding/locale/brand.properties"
    );
    let telemetryBundle = Services.strings.createBundle(
      "chrome://messenger/locale/telemetry.properties"
    );

    let productName = brandBundle.GetStringFromName("brandFullName");
    let serverOwner = Services.prefs.getCharPref(
      "toolkit.telemetry.server_owner"
    );
    let telemetryText = telemetryBundle.formatStringFromName("telemetryText", [
      productName,
      serverOwner,
    ]);

    // TODO: sync up this bar with Firefox:
    // https://searchfox.org/mozilla-central/rev/227f22acef5c4865503bde9f835452bf38332c8e/browser/locales/en-US/chrome/browser/browser.properties#697-698
    let buttons = [
      {
        label: telemetryBundle.GetStringFromName("telemetryLinkLabel"),
        popup: null,
        callback: () => {
          openOptionsDialog("panePrivacy", "privacyDataCollectionCategory");
        },
      },
    ];

    let notification = this.msgNotificationBar.appendNotification(
      "telemetry",
      {
        label: telemetryText,
        priority: this.msgNotificationBar.PRIORITY_INFO_LOW,
      },
      buttons
    );
    // Arbitrary number, just so bar sticks around for a bit.
    notification.persistence = 3;
  },

  /**
   * Looks at the existing prefs and determines if we should show about:rights
   * or not.
   *
   * This is controlled by two prefs:
   *
   *   mail.rights.override
   *     If this pref is set to false, always show the about:rights
   *     notification.
   *     If this pref is set to true, never show the about:rights notification.
   *     If the pref doesn't exist, then we fallback to checking
   *     mail.rights.version.
   *
   *   mail.rights.version
   *     If this pref isn't set or the value is less than the current version
   *     then we show the about:rights notification.
   */
  shouldShowAboutRightsNotification() {
    try {
      return !Services.prefs.getBoolPref("mail.rights.override");
    } catch (e) {}

    return (
      Services.prefs.getIntPref("mail.rights.version") <
      this._kAboutRightsVersion
    );
  },

  async showAboutRightsNotification() {
    var rightsBundle = Services.strings.createBundle(
      "chrome://messenger/locale/aboutRights.properties"
    );

    var buttons = [
      {
        label: rightsBundle.GetStringFromName("buttonLabel"),
        accessKey: rightsBundle.GetStringFromName("buttonAccessKey"),
        popup: null,
        callback(aNotificationBar, aButton) {
          // Show the about:rights tab
          document.getElementById("tabmail").openTab("contentTab", {
            url: "about:rights",
          });
        },
      },
    ];

    let notifyRightsText = await document.l10n.formatValue(
      "about-rights-notification-text"
    );
    let notification = this.msgNotificationBar.appendNotification(
      "about-rights",
      {
        label: notifyRightsText,
        priority: this.msgNotificationBar.PRIORITY_INFO_LOW,
      },
      buttons
    );
    // Arbitrary number, just so bar sticks around for a bit.
    notification.persistence = 3;

    // Set the pref to say we've displayed the notification.
    Services.prefs.setIntPref("mail.rights.version", this._kAboutRightsVersion);
  },

  /**
   * Determine if we should load fav icons or not.
   *
   * @param aURI  An nsIURI containing the current url.
   */
  _shouldLoadFavIcon(aURI) {
    return (
      aURI &&
      Services.prefs.getBoolPref("browser.chrome.site_icons") &&
      Services.prefs.getBoolPref("browser.chrome.favicons") &&
      "schemeIs" in aURI &&
      (aURI.schemeIs("http") || aURI.schemeIs("https"))
    );
  },

  /**
   * Tries to use the default favicon for a webpage for the specified tab.
   * We'll use the site's favicon.ico if prefs allow us to.
   */
  useDefaultFavIcon(aTab) {
    // Use documentURI in the check for shouldLoadFavIcon so that we do the
    // right thing with about:-style error pages.
    let docURIObject = aTab.browser.documentURI;
    let icon = null;
    if (this._shouldLoadFavIcon(docURIObject)) {
      icon = docURIObject.prePath + "/favicon.ico";
    }

    this.setFavIcon(aTab, icon);
  },

  /**
   * This sets the specified tab to load and display the given icon for the
   * page shown in the browser. It is assumed that the preferences have already
   * been checked before calling this function appropriately.
   *
   * @param aTab  The tab to set the icon for.
   * @param aIcon A string based URL of the icon to try and load.
   */
  setFavIcon(aTab, aIcon) {
    if (aIcon) {
      PlacesUtils.favicons.setAndFetchFaviconForPage(
        aTab.browser.currentURI,
        Services.io.newURI(aIcon),
        false,
        PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
        null,
        aTab.browser.contentPrincipal
      );
    }
    document
      .getElementById("tabmail")
      .setTabFavIcon(
        aTab,
        aIcon,
        "chrome://messenger/skin/icons/new/compact/draft.svg"
      );
  },

  browserForward() {
    let tabmail = document.getElementById("tabmail");
    if (
      !["contentTab", "mail3PaneTab"].includes(
        tabmail?.currentTabInfo.mode.name
      )
    ) {
      return;
    }
    let browser = tabmail.getBrowserForSelectedTab();
    if (!browser) {
      return;
    }
    if (browser.webNavigation) {
      browser.webNavigation.goForward();
    }
  },

  browserBack() {
    let tabmail = document.getElementById("tabmail");
    if (
      !["contentTab", "mail3PaneTab"].includes(
        tabmail?.currentTabInfo.mode.name
      )
    ) {
      return;
    }
    let browser = tabmail.getBrowserForSelectedTab();
    if (!browser) {
      return;
    }
    if (browser.webNavigation) {
      browser.webNavigation.goBack();
    }
  },
};