summaryrefslogtreecommitdiffstats
path: root/browser/components/places/PlacesUIUtils.sys.mjs
blob: 415a97ec6c74cd51ab02c07ef43bd68d035ee4cc (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
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* 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";

import { clearTimeout, setTimeout } from "resource://gre/modules/Timer.sys.mjs";
import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  CLIENT_NOT_CONFIGURED: "resource://services-sync/constants.sys.mjs",
  BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.sys.mjs",
  CustomizableUI: "resource:///modules/CustomizableUI.sys.mjs",
  MigrationUtils: "resource:///modules/MigrationUtils.sys.mjs",
  OpenInTabsUtils: "resource:///modules/OpenInTabsUtils.sys.mjs",
  PlacesTransactions: "resource://gre/modules/PlacesTransactions.sys.mjs",
  PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
  PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
  Weave: "resource://services-sync/main.sys.mjs",
});

const gInContentProcess =
  Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
const FAVICON_REQUEST_TIMEOUT = 60 * 1000;
// Map from windows to arrays of data about pending favicon loads.
let gFaviconLoadDataMap = new Map();

const ITEM_CHANGED_BATCH_NOTIFICATION_THRESHOLD = 10;

// copied from utilityOverlay.js
const TAB_DROP_TYPE = "application/x-moz-tabbrowser-tab";

let InternalFaviconLoader = {
  /**
   * Actually cancel the request, and clear the timeout for cancelling it.
   *
   * @param {object} options
   *   The options object containing:
   * @param {object} options.uri
   *   The URI of the favicon to cancel.
   * @param {number} options.innerWindowID
   *   The inner window ID of the window. Unused.
   * @param {number} options.timerID
   *   The timer ID of the timeout to be cancelled
   * @param {*} options.callback
   *   The request callback
   * @param {string} reason
   *   The reason for cancelling the request.
   */
  _cancelRequest({ uri, innerWindowID, timerID, callback }, reason) {
    // Break cycle
    let request = callback.request;
    delete callback.request;
    // Ensure we don't time out.
    clearTimeout(timerID);
    try {
      request.cancel();
    } catch (ex) {
      console.error(
        `When cancelling a request for ${uri.spec} because ${reason}, it was already canceled!`
      );
    }
  },

  /**
   * Called for every inner that gets destroyed, only in the parent process.
   *
   * @param {number} innerID
   *   The innerID of the window.
   */
  removeRequestsForInner(innerID) {
    for (let [window, loadDataForWindow] of gFaviconLoadDataMap) {
      let newLoadDataForWindow = loadDataForWindow.filter(loadData => {
        let innerWasDestroyed = loadData.innerWindowID == innerID;
        if (innerWasDestroyed) {
          this._cancelRequest(
            loadData,
            "the inner window was destroyed or a new favicon was loaded for it"
          );
        }
        // Keep the items whose inner is still alive.
        return !innerWasDestroyed;
      });
      // Map iteration with for...of is safe against modification, so
      // now just replace the old value:
      gFaviconLoadDataMap.set(window, newLoadDataForWindow);
    }
  },

  /**
   * Called when a toplevel chrome window unloads. We use this to tidy up after ourselves,
   * avoid leaks, and cancel any remaining requests. The last part should in theory be
   * handled by the inner-window-destroyed handlers. We clean up just to be on the safe side.
   *
   * @param {DOMWindow} win
   *   The window that was unloaded.
   */
  onUnload(win) {
    let loadDataForWindow = gFaviconLoadDataMap.get(win);
    if (loadDataForWindow) {
      for (let loadData of loadDataForWindow) {
        this._cancelRequest(loadData, "the chrome window went away");
      }
    }
    gFaviconLoadDataMap.delete(win);
  },

  /**
   * Remove a particular favicon load's loading data from our map tracking
   * load data per chrome window.
   *
   * @param {DOMWindow} win
   *   the chrome window in which we should look for this load
   * @param {object} filterData
   *   the data we should use to find this particular load to remove.
   * @param {number} filterData.innerWindowID
   *   The inner window ID of the window.
   * @param {string} filterData.uri
   *   The URI of the favicon to cancel.
   * @param {*} filterData.callback
   *   The request callback
   *
   * @returns {object|null}
   *   the loadData object we removed, or null if we didn't find any.
   */
  _removeLoadDataFromWindowMap(win, { innerWindowID, uri, callback }) {
    let loadDataForWindow = gFaviconLoadDataMap.get(win);
    if (loadDataForWindow) {
      let itemIndex = loadDataForWindow.findIndex(loadData => {
        return (
          loadData.innerWindowID == innerWindowID &&
          loadData.uri.equals(uri) &&
          loadData.callback.request == callback.request
        );
      });
      if (itemIndex != -1) {
        let loadData = loadDataForWindow[itemIndex];
        loadDataForWindow.splice(itemIndex, 1);
        return loadData;
      }
    }
    return null;
  },

  /**
   * Create a function to use as a nsIFaviconDataCallback, so we can remove cancelling
   * information when the request succeeds. Note that right now there are some edge-cases,
   * such as about: URIs with chrome:// favicons where the success callback is not invoked.
   * This is OK: we will 'cancel' the request after the timeout (or when the window goes
   * away) but that will be a no-op in such cases.
   *
   * @param {DOMWindow} win
   *   The chrome window in which the request was made.
   * @param {number} id
   *   The inner window ID of the window.
   * @returns {object}
   */
  _makeCompletionCallback(win, id) {
    return {
      onComplete(uri) {
        let loadData = InternalFaviconLoader._removeLoadDataFromWindowMap(win, {
          uri,
          innerWindowID: id,
          callback: this,
        });
        if (loadData) {
          clearTimeout(loadData.timerID);
        }
        delete this.request;
      },
    };
  },

  ensureInitialized() {
    if (this._initialized) {
      return;
    }
    this._initialized = true;

    Services.obs.addObserver(windowGlobal => {
      this.removeRequestsForInner(windowGlobal.innerWindowId);
    }, "window-global-destroyed");
  },

  loadFavicon(browser, principal, pageURI, uri, expiration, iconURI) {
    this.ensureInitialized();
    let { ownerGlobal: win, innerWindowID } = browser;
    if (!gFaviconLoadDataMap.has(win)) {
      gFaviconLoadDataMap.set(win, []);
      let unloadHandler = event => {
        let doc = event.target;
        let eventWin = doc.defaultView;
        if (eventWin == win) {
          win.removeEventListener("unload", unloadHandler);
          this.onUnload(win);
        }
      };
      win.addEventListener("unload", unloadHandler, true);
    }

    // First we do the actual setAndFetch call:
    let loadType = lazy.PrivateBrowsingUtils.isWindowPrivate(win)
      ? lazy.PlacesUtils.favicons.FAVICON_LOAD_PRIVATE
      : lazy.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE;
    let callback = this._makeCompletionCallback(win, innerWindowID);

    if (iconURI && iconURI.schemeIs("data")) {
      expiration = lazy.PlacesUtils.toPRTime(expiration);
      lazy.PlacesUtils.favicons.replaceFaviconDataFromDataURL(
        uri,
        iconURI.spec,
        expiration,
        principal
      );
    }

    let request = lazy.PlacesUtils.favicons.setAndFetchFaviconForPage(
      pageURI,
      uri,
      false,
      loadType,
      callback,
      principal
    );

    // Now register the result so we can cancel it if/when necessary.
    if (!request) {
      // The favicon service can return with success but no-op (and leave request
      // as null) if the icon is the same as the page (e.g. for images) or if it is
      // the favicon for an error page. In this case, we do not need to do anything else.
      return;
    }
    callback.request = request;
    let loadData = { innerWindowID, uri, callback };
    loadData.timerID = setTimeout(() => {
      this._cancelRequest(loadData, "it timed out");
      this._removeLoadDataFromWindowMap(win, loadData);
    }, FAVICON_REQUEST_TIMEOUT);
    let loadDataForWindow = gFaviconLoadDataMap.get(win);
    loadDataForWindow.push(loadData);
  },
};

/**
 * Collects all information for a bookmark and performs editmethods
 */
class BookmarkState {
  /**
   * Construct a new BookmarkState.
   *
   * @param {object} options
   *   The constructor options.
   * @param {object} options.info
   *   Either a result node or a node-like object representing the item to be edited.
   * @param {string} [options.tags]
   *   Tags (if any) for the bookmark in a comma separated string. Empty tags are
   *   skipped
   * @param {string} [options.keyword]
   *   Existing (if there are any) keyword for bookmark
   * @param {boolean} [options.isFolder]
   *   If the item is a folder.
   * @param {Array<{ title: string; url: nsIURI; }>} [options.children]
   *   The list of child URIs to bookmark within the folder.
   * @param {boolean} [options.autosave]
   *   If changes to bookmark fields should be saved immediately after calling
   *   its respective "changed" method, rather than waiting for save() to be
   *   called.
   * @param {number} [options.index]
   *   The insertion point index of the bookmark.
   */
  constructor({
    info,
    tags = "",
    keyword = "",
    isFolder = false,
    children = [],
    autosave = false,
    index,
  }) {
    this._guid = info.itemGuid;
    this._postData = info.postData;
    this._isTagContainer = info.isTag;
    this._bulkTaggingUrls = info.uris?.map(uri => uri.spec);
    this._isFolder = isFolder;
    this._children = children;
    this._autosave = autosave;

    // Original Bookmark
    this._originalState = {
      title: this._isTagContainer ? info.tag : info.title,
      uri: info.uri?.spec,
      tags: tags
        .trim()
        .split(/\s*,\s*/)
        .filter(tag => !!tag.length),
      keyword,
      parentGuid: info.parentGuid,
      index,
    };

    // Edited bookmark
    this._newState = {};
  }

  /**
   * Save edited title for the bookmark
   *
   * @param {string} title
   *   The title of the bookmark
   */
  async _titleChanged(title) {
    this._newState.title = title;
    await this._maybeSave();
  }

  /**
   * Save edited location for the bookmark
   *
   * @param {string} location
   *   The location of the bookmark
   */
  async _locationChanged(location) {
    this._newState.uri = location;
    await this._maybeSave();
  }

  /**
   * Save edited tags for the bookmark
   *
   * @param {string} tags
   *    Comma separated list of tags
   */
  async _tagsChanged(tags) {
    this._newState.tags = tags;
    await this._maybeSave();
  }

  /**
   * Save edited keyword for the bookmark
   *
   * @param {string} keyword
   *   The keyword of the bookmark
   */
  async _keywordChanged(keyword) {
    this._newState.keyword = keyword;
    await this._maybeSave();
  }

  /**
   * Save edited parentGuid for the bookmark
   *
   * @param {string} parentGuid
   *   The parentGuid of the bookmark
   */
  async _parentGuidChanged(parentGuid) {
    this._newState.parentGuid = parentGuid;
    await this._maybeSave();
  }

  /**
   * Save changes if autosave is enabled.
   */
  async _maybeSave() {
    if (this._autosave) {
      await this.save();
    }
  }

  /**
   * Create a new bookmark.
   *
   * @returns {string} The bookmark's GUID.
   */
  async _createBookmark() {
    let transactions = [
      lazy.PlacesTransactions.NewBookmark({
        parentGuid: this.parentGuid,
        tags: this._newState.tags,
        title: this._newState.title ?? this._originalState.title,
        url: this._newState.uri ?? this._originalState.uri,
        index: this._originalState.index,
      }),
    ];
    if (this._newState.keyword) {
      transactions.push(previousResults =>
        lazy.PlacesTransactions.EditKeyword({
          guid: previousResults[0],
          keyword: this._newState.keyword,
          postData: this._postData,
        })
      );
    }
    let results = await lazy.PlacesTransactions.batch(
      transactions,
      "BookmarkState::createBookmark"
    );
    this._guid = results?.[0];
    return this._guid;
  }

  /**
   * Create a new folder.
   *
   * @returns {string} The folder's GUID.
   */
  async _createFolder() {
    this._guid = await lazy.PlacesTransactions.NewFolder({
      parentGuid: this.parentGuid,
      title: this._newState.title ?? this._originalState.title,
      children: this._children,
      index: this._originalState.index,
    }).transact();
    return this._guid;
  }

  get parentGuid() {
    return this._newState.parentGuid ?? this._originalState.parentGuid;
  }

  /**
   * Save() API function for bookmark.
   *
   * @returns {string} bookmark.guid
   */
  async save() {
    if (this._guid === lazy.PlacesUtils.bookmarks.unsavedGuid) {
      return this._isFolder ? this._createFolder() : this._createBookmark();
    }

    if (!Object.keys(this._newState).length) {
      return this._guid;
    }

    if (this._isTagContainer && this._newState.title) {
      await lazy.PlacesTransactions.RenameTag({
        oldTag: this._originalState.title,
        tag: this._newState.title,
      })
        .transact()
        .catch(console.error);
      return this._guid;
    }

    let url = this._newState.uri || this._originalState.uri;
    let transactions = [];

    if (this._newState.uri) {
      transactions.push(
        lazy.PlacesTransactions.EditUrl({
          guid: this._guid,
          url,
        })
      );
    }

    for (const [key, value] of Object.entries(this._newState)) {
      switch (key) {
        case "title":
          transactions.push(
            lazy.PlacesTransactions.EditTitle({
              guid: this._guid,
              title: value,
            })
          );
          break;
        case "tags":
          const newTags = value.filter(
            tag => !this._originalState.tags.includes(tag)
          );
          const removedTags = this._originalState.tags.filter(
            tag => !value.includes(tag)
          );
          if (newTags.length) {
            transactions.push(
              lazy.PlacesTransactions.Tag({
                urls: this._bulkTaggingUrls || [url],
                tags: newTags,
              })
            );
          }
          if (removedTags.length) {
            transactions.push(
              lazy.PlacesTransactions.Untag({
                urls: this._bulkTaggingUrls || [url],
                tags: removedTags,
              })
            );
          }
          break;
        case "keyword":
          transactions.push(
            lazy.PlacesTransactions.EditKeyword({
              guid: this._guid,
              keyword: value,
              postData: this._postData,
              oldKeyword: this._originalState.keyword,
            })
          );
          break;
        case "parentGuid":
          transactions.push(
            lazy.PlacesTransactions.Move({
              guid: this._guid,
              newParentGuid: this._newState.parentGuid,
            })
          );
          break;
      }
    }
    if (transactions.length) {
      await lazy.PlacesTransactions.batch(transactions, "BookmarkState::save");
    }

    this._originalState = { ...this._originalState, ...this._newState };
    this._newState = {};
    return this._guid;
  }
}

export var PlacesUIUtils = {
  BookmarkState,
  _bookmarkToolbarTelemetryListening: false,
  LAST_USED_FOLDERS_META_KEY: "bookmarks/lastusedfolders",

  lastContextMenuTriggerNode: null,

  // This allows to await for all the relevant bookmark changes to be applied
  // when a bookmark dialog is closed. It is resolved to the bookmark guid,
  // if a bookmark was created or modified.
  lastBookmarkDialogDeferred: null,

  /**
   * Obfuscates a place: URL to use it in xulstore without the risk of
   leaking browsing information. Uses md5 to hash the query string.
   *
   * @param {URL} url
   *        the URL for xulstore with place: key pairs.
   * @returns {string} "place:[md5_hash]" hashed url
   */

  obfuscateUrlForXulStore(url) {
    if (!url.startsWith("place:")) {
      throw new Error("Method must be used to only obfuscate place: uris!");
    }
    let urlNoProtocol = url.substring(url.indexOf(":") + 1);
    let hashedURL = lazy.PlacesUtils.md5(urlNoProtocol);

    return `place:${hashedURL}`;
  },

  /**
   * Shows the bookmark dialog corresponding to the specified info.
   *
   * @param {object} aInfo
   *        Describes the item to be edited/added in the dialog.
   *        See documentation at the top of bookmarkProperties.js
   * @param {DOMWindow} [aParentWindow]
   *        Owner window for the new dialog.
   *
   * @see documentation at the top of bookmarkProperties.js
   * @returns {string} The guid of the item that was created or edited,
   *                   undefined otherwise.
   */
  async showBookmarkDialog(aInfo, aParentWindow = null) {
    this.lastBookmarkDialogDeferred = Promise.withResolvers();

    let dialogURL = "chrome://browser/content/places/bookmarkProperties.xhtml";
    let features = "centerscreen,chrome,modal,resizable=no";
    let bookmarkGuid;

    if (!aParentWindow) {
      aParentWindow = Services.wm.getMostRecentWindow(null);
    }

    if (aParentWindow.gDialogBox) {
      await aParentWindow.gDialogBox.open(dialogURL, aInfo);
    } else {
      aParentWindow.openDialog(dialogURL, "", features, aInfo);
    }

    if (aInfo.bookmarkState) {
      bookmarkGuid = await aInfo.bookmarkState.save();
      this.lastBookmarkDialogDeferred.resolve(bookmarkGuid);
      return bookmarkGuid;
    }
    bookmarkGuid = undefined;
    this.lastBookmarkDialogDeferred.resolve(bookmarkGuid);
    return bookmarkGuid;
  },

  /**
   * Bookmarks one or more pages. If there is more than one, this will create
   * the bookmarks in a new folder.
   *
   * @param {Array.<nsIURI>} URIList
   *   The list of URIs to bookmark.
   * @param {Array.<string>} [hiddenRows]
   *   An array of rows to be hidden.
   * @param {DOMWindow} [win]
   *   The window to use as the parent to display the bookmark dialog.
   */
  async showBookmarkPagesDialog(URIList, hiddenRows = [], win = null) {
    if (!URIList.length) {
      return;
    }

    const bookmarkDialogInfo = { action: "add", hiddenRows };
    if (URIList.length > 1) {
      bookmarkDialogInfo.type = "folder";
      bookmarkDialogInfo.URIList = URIList;
    } else {
      bookmarkDialogInfo.type = "bookmark";
      bookmarkDialogInfo.title = URIList[0].title;
      bookmarkDialogInfo.uri = URIList[0].uri;
    }

    await PlacesUIUtils.showBookmarkDialog(bookmarkDialogInfo, win);
  },

  /**
   * set and fetch a favicon. Can only be used from the parent process.
   *
   * @param {object} browser
   *        The XUL browser element for which we're fetching a favicon.
   * @param {Principal} principal
   *        The loading principal to use for the fetch.
   * @param {URI} pageURI
   *        The page URI associated to this favicon load.
   * @param {URI} uri
   *        The URI to fetch.
   * @param {number} expiration
   *        An optional expiration time.
   * @param {URI} iconURI
   *        An optional data: URI holding the icon's data.
   */
  loadFavicon(
    browser,
    principal,
    pageURI,
    uri,
    expiration = 0,
    iconURI = null
  ) {
    if (gInContentProcess) {
      throw new Error("Can't track loads from within the child process!");
    }
    InternalFaviconLoader.loadFavicon(
      browser,
      principal,
      pageURI,
      uri,
      expiration,
      iconURI
    );
  },

  /**
   * Returns the closet ancestor places view for the given DOM node
   *
   * @param {DOMNode} aNode
   *        a DOM node
   * @returns {DOMNode} the closest ancestor places view if exists, null otherwsie.
   */
  getViewForNode: function PUIU_getViewForNode(aNode) {
    let node = aNode;

    if (Cu.isDeadWrapper(node)) {
      return null;
    }

    if (node.localName == "panelview" && node._placesView) {
      return node._placesView;
    }

    // The view for a <menu> of which its associated menupopup is a places
    // view, is the menupopup.
    if (
      node.localName == "menu" &&
      !node._placesNode &&
      node.menupopup._placesView
    ) {
      return node.menupopup._placesView;
    }

    while (Element.isInstance(node)) {
      if (node._placesView) {
        return node._placesView;
      }
      if (
        node.localName == "tree" &&
        node.getAttribute("is") == "places-tree"
      ) {
        return node;
      }

      node = node.parentNode;
    }

    return null;
  },

  /**
   * Returns the active PlacesController for a given command.
   *
   * @param {DOMWindow} win The window containing the affected view
   * @param {string} command The command
   * @returns {PlacesController} a places controller
   */
  getControllerForCommand(win, command) {
    // If we're building a context menu for a non-focusable view, for example
    // a menupopup, we must return the view that triggered the context menu.
    let popupNode = PlacesUIUtils.lastContextMenuTriggerNode;
    if (popupNode) {
      let isManaged = !!popupNode.closest("#managed-bookmarks");
      if (isManaged) {
        return this.managedBookmarksController;
      }
      let view = this.getViewForNode(popupNode);
      if (view && view._contextMenuShown) {
        return view.controllers.getControllerForCommand(command);
      }
    }

    // When we're not building a context menu, only focusable views
    // are possible.  Thus, we can safely use the command dispatcher.
    let controller =
      win.top.document.commandDispatcher.getControllerForCommand(command);
    return controller || null;
  },

  /**
   * Update all the Places commands for the given window.
   *
   * @param {DOMWindow} win The window to update.
   */
  updateCommands(win) {
    // Get the controller for one of the places commands.
    let controller = this.getControllerForCommand(win, "placesCmd_open");
    for (let command of [
      "placesCmd_open",
      "placesCmd_open:window",
      "placesCmd_open:privatewindow",
      "placesCmd_open:tab",
      "placesCmd_new:folder",
      "placesCmd_new:bookmark",
      "placesCmd_new:separator",
      "placesCmd_show:info",
      "placesCmd_reload",
      "placesCmd_sortBy:name",
      "placesCmd_cut",
      "placesCmd_copy",
      "placesCmd_paste",
      "placesCmd_delete",
      "placesCmd_showInFolder",
    ]) {
      win.goSetCommandEnabled(
        command,
        controller && controller.isCommandEnabled(command)
      );
    }
  },

  /**
   * Executes the given command on the currently active controller.
   *
   * @param {DOMWindow} win The window containing the affected view
   * @param {string} command The command to execute
   */
  doCommand(win, command) {
    let controller = this.getControllerForCommand(win, command);
    if (controller && controller.isCommandEnabled(command)) {
      controller.doCommand(command);
    }
  },

  /**
   * By calling this before visiting an URL, the visit will be associated to a
   * TRANSITION_TYPED transition (if there is no a referrer).
   * This is used when visiting pages from the history menu, history sidebar,
   * url bar, url autocomplete results, and history searches from the places
   * organizer.  If this is not called visits will be marked as
   * TRANSITION_LINK.
   *
   * @param {string} aURL
   *   The URL to mark as typed.
   */
  markPageAsTyped: function PUIU_markPageAsTyped(aURL) {
    lazy.PlacesUtils.history.markPageAsTyped(
      Services.uriFixup.getFixupURIInfo(aURL).preferredURI
    );
  },

  /**
   * By calling this before visiting an URL, the visit will be associated to a
   * TRANSITION_BOOKMARK transition.
   * This is used when visiting pages from the bookmarks menu,
   * personal toolbar, and bookmarks from within the places organizer.
   * If this is not called visits will be marked as TRANSITION_LINK.
   *
   * @param {string} aURL
   *   The URL to mark as TRANSITION_BOOKMARK.
   */
  markPageAsFollowedBookmark: function PUIU_markPageAsFollowedBookmark(aURL) {
    lazy.PlacesUtils.history.markPageAsFollowedBookmark(
      Services.uriFixup.getFixupURIInfo(aURL).preferredURI
    );
  },

  /**
   * By calling this before visiting an URL, any visit in frames will be
   * associated to a TRANSITION_FRAMED_LINK transition.
   * This is actually used to distinguish user-initiated visits in frames
   * so automatic visits can be correctly ignored.
   *
   * @param {string} aURL
   *   The URL to mark as TRANSITION_FRAMED_LINK.
   */
  markPageAsFollowedLink: function PUIU_markPageAsFollowedLink(aURL) {
    lazy.PlacesUtils.history.markPageAsFollowedLink(
      Services.uriFixup.getFixupURIInfo(aURL).preferredURI
    );
  },

  /**
   * Sets the character-set for a page. The character set will not be saved
   * if the window is determined to be a private browsing window.
   *
   * @param {string|URL|nsIURI} url The URL of the page to set the charset on.
   * @param {string} charset character-set value.
   * @param {DOMWindow} window The window that the charset is being set from.
   * @returns {Promise}
   */
  async setCharsetForPage(url, charset, window) {
    if (lazy.PrivateBrowsingUtils.isWindowPrivate(window)) {
      return;
    }

    // UTF-8 is the default. If we are passed the value then set it to null,
    // to ensure any charset is removed from the database.
    if (charset.toLowerCase() == "utf-8") {
      charset = null;
    }

    await lazy.PlacesUtils.history.update({
      url,
      annotations: new Map([[lazy.PlacesUtils.CHARSET_ANNO, charset]]),
    });
  },

  /**
   * Allows opening of javascript/data URI only if the given node is
   * bookmarked (see bug 224521).
   *
   * @param {object} aURINode
   *        a URI node
   * @param {DOMWindow} aWindow
   *        a window on which a potential error alert is shown on.
   * @returns {boolean} true if it's safe to open the node in the browser, false otherwise.
   *
   */
  checkURLSecurity: function PUIU_checkURLSecurity(aURINode, aWindow) {
    if (lazy.PlacesUtils.nodeIsBookmark(aURINode)) {
      return true;
    }

    var uri = Services.io.newURI(aURINode.uri);
    if (uri.schemeIs("javascript") || uri.schemeIs("data")) {
      const [title, errorStr] =
        PlacesUIUtils.promptLocalization.formatValuesSync([
          "places-error-title",
          "places-load-js-data-url-error",
        ]);
      Services.prompt.alert(aWindow, title, errorStr);
      return false;
    }
    return true;
  },

  /**
   * Check whether or not the given node represents a removable entry (either in
   * history or in bookmarks).
   *
   * @param {object} aNode
   *        a node, except the root node of a query.
   * @returns {boolean} true if the aNode represents a removable entry, false otherwise.
   */
  canUserRemove(aNode) {
    let parentNode = aNode.parent;
    if (!parentNode) {
      // canUserRemove doesn't accept root nodes.
      return false;
    }

    // Is it a query pointing to one of the special root folders?
    if (lazy.PlacesUtils.nodeIsQuery(parentNode)) {
      if (lazy.PlacesUtils.nodeIsFolder(aNode)) {
        let guid = lazy.PlacesUtils.getConcreteItemGuid(aNode);
        // If the parent folder is not a folder, it must be a query, and so this node
        // cannot be removed.
        if (lazy.PlacesUtils.isRootItem(guid)) {
          return false;
        }
      } else if (lazy.PlacesUtils.isVirtualLeftPaneItem(aNode.bookmarkGuid)) {
        // If the item is a left-pane top-level item, it can't be removed.
        return false;
      }
    }

    // If it's not a bookmark, or it's child of a query, we can remove it.
    if (aNode.itemId == -1 || lazy.PlacesUtils.nodeIsQuery(parentNode)) {
      return true;
    }

    // Otherwise it has to be a child of an editable folder.
    return !this.isFolderReadOnly(parentNode);
  },

  /**
   * DO NOT USE THIS API IN ADDONS. IT IS VERY LIKELY TO CHANGE WHEN THE SWITCH
   * TO GUIDS IS COMPLETE (BUG 1071511).
   *
   * Check whether or not the given Places node points to a folder which
   * should not be modified by the user (i.e. its children should be unremovable
   * and unmovable, new children should be disallowed, etc).
   * These semantics are not inherited, meaning that read-only folder may
   * contain editable items (for instance, the places root is read-only, but all
   * of its direct children aren't).
   *
   * You should only pass folder nodes.
   *
   * @param {object} placesNode
   *        any folder result node.
   * @throws if placesNode is not a folder result node or views is invalid.
   * @returns {boolean} true if placesNode is a read-only folder, false otherwise.
   */
  isFolderReadOnly(placesNode) {
    if (
      typeof placesNode != "object" ||
      !lazy.PlacesUtils.nodeIsFolder(placesNode)
    ) {
      throw new Error("invalid value for placesNode");
    }

    return (
      lazy.PlacesUtils.getConcreteItemGuid(placesNode) ==
      lazy.PlacesUtils.bookmarks.rootGuid
    );
  },

  /**
   * @param {Array<object>} aItemsToOpen
   *   needs to be an array of objects of the form:
   *   {uri: string, isBookmark: boolean}
   * @param {object} aEvent
   *   The associated event triggering the open.
   * @param {DOMWindow} aWindow
   *   The window associated with the event.
   */
  openTabset(aItemsToOpen, aEvent, aWindow) {
    if (!aItemsToOpen.length) {
      return;
    }

    let browserWindow = getBrowserWindow(aWindow);
    var urls = [];
    let isPrivate =
      browserWindow && lazy.PrivateBrowsingUtils.isWindowPrivate(browserWindow);
    for (let item of aItemsToOpen) {
      urls.push(item.uri);
      if (isPrivate) {
        continue;
      }

      if (item.isBookmark) {
        this.markPageAsFollowedBookmark(item.uri);
      } else {
        this.markPageAsTyped(item.uri);
      }
    }

    // whereToOpenLink doesn't return "window" when there's no browser window
    // open (Bug 630255).
    var where = browserWindow
      ? browserWindow.whereToOpenLink(aEvent, false, true)
      : "window";
    if (where == "window") {
      // There is no browser window open, thus open a new one.
      let args = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
      let stringsToLoad = Cc["@mozilla.org/array;1"].createInstance(
        Ci.nsIMutableArray
      );
      urls.forEach(url =>
        stringsToLoad.appendElement(lazy.PlacesUtils.toISupportsString(url))
      );
      args.appendElement(stringsToLoad);

      let features = "chrome,dialog=no,all";
      if (isPrivate) {
        features += ",private";
      }

      browserWindow = Services.ww.openWindow(
        aWindow,
        AppConstants.BROWSER_CHROME_URL,
        null,
        features,
        args
      );
      return;
    }

    var loadInBackground = where == "tabshifted";
    // For consistency, we want all the bookmarks to open in new tabs, instead
    // of having one of them replace the currently focused tab.  Hence we call
    // loadTabs with aReplace set to false.
    browserWindow.gBrowser.loadTabs(urls, {
      inBackground: loadInBackground,
      replace: false,
      triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
    });
  },

  /**
   * Loads a selected node's or nodes' URLs in tabs,
   * warning the user when lots of URLs are being opened
   *
   * @param {object | Array} nodeOrNodes
   *          Contains the node or nodes that we're opening in tabs
   * @param {event} event
   *          The DOM mouse/key event with modifier keys set that track the
   *          user's preferred destination window or tab.
   * @param {object} view
   *          The current view that contains the node or nodes selected for
   *          opening
   */
  openMultipleLinksInTabs(nodeOrNodes, event, view) {
    let window = view.ownerWindow;
    let urlsToOpen = [];

    if (lazy.PlacesUtils.nodeIsContainer(nodeOrNodes)) {
      urlsToOpen = lazy.PlacesUtils.getURLsForContainerNode(nodeOrNodes);
    } else {
      for (var i = 0; i < nodeOrNodes.length; i++) {
        // Skip over separators and folders.
        if (lazy.PlacesUtils.nodeIsURI(nodeOrNodes[i])) {
          urlsToOpen.push({
            uri: nodeOrNodes[i].uri,
            isBookmark: lazy.PlacesUtils.nodeIsBookmark(nodeOrNodes[i]),
          });
        }
      }
    }
    if (lazy.OpenInTabsUtils.confirmOpenInTabs(urlsToOpen.length, window)) {
      if (window.updateTelemetry) {
        window.updateTelemetry(urlsToOpen);
      }
      this.openTabset(urlsToOpen, event, window);
    }
  },

  /**
   * Loads the node's URL in the appropriate tab or window given the
   * user's preference specified by modifier keys tracked by a
   * DOM mouse/key event.
   *
   * @param {object} aNode
   *          An uri result node.
   * @param {object} aEvent
   *          The DOM mouse/key event with modifier keys set that track the
   *          user's preferred destination window or tab.
   */
  openNodeWithEvent: function PUIU_openNodeWithEvent(aNode, aEvent) {
    let window = aEvent.target.ownerGlobal;

    let where = window.whereToOpenLink(aEvent, false, true);
    if (this.loadBookmarksInTabs && lazy.PlacesUtils.nodeIsBookmark(aNode)) {
      if (where == "current" && !aNode.uri.startsWith("javascript:")) {
        where = "tab";
      }
      let browserWindow = getBrowserWindow(window);
      if (where == "tab" && browserWindow?.gBrowser.selectedTab.isEmpty) {
        where = "current";
      }
    }

    this._openNodeIn(aNode, where, window);
  },

  /**
   * Loads the node's URL in the appropriate tab or window.
   * see also URILoadingHelper's openWebLinkIn
   *
   * @param {object} aNode
   *        An uri result node.
   * @param {string} aWhere
   *        Where to open the URL.
   * @param {object} aView
   *        The associated view of the node being opened.
   * @param {boolean} aPrivate
   *        True if the window being opened is private.
   */
  openNodeIn: function PUIU_openNodeIn(aNode, aWhere, aView, aPrivate) {
    let window = aView.ownerWindow;
    this._openNodeIn(aNode, aWhere, window, { aPrivate });
  },

  _openNodeIn: function PUIU__openNodeIn(
    aNode,
    aWhere,
    aWindow,
    { aPrivate = false, userContextId = 0 } = {}
  ) {
    if (
      aNode &&
      lazy.PlacesUtils.nodeIsURI(aNode) &&
      this.checkURLSecurity(aNode, aWindow)
    ) {
      let isBookmark = lazy.PlacesUtils.nodeIsBookmark(aNode);

      if (!lazy.PrivateBrowsingUtils.isWindowPrivate(aWindow)) {
        if (isBookmark) {
          this.markPageAsFollowedBookmark(aNode.uri);
        } else {
          this.markPageAsTyped(aNode.uri);
        }
      } else {
        // This is a targeted fix for bug 1792163, where it was discovered
        // that if you open the Library from a Private Browsing window, and then
        // use the "Open in New Window" context menu item to open a new window,
        // that the window will open under the wrong icon on the Windows taskbar.
        aPrivate = true;
      }

      const isJavaScriptURL = aNode.uri.startsWith("javascript:");
      aWindow.openTrustedLinkIn(aNode.uri, aWhere, {
        allowPopups: isJavaScriptURL,
        inBackground: this.loadBookmarksInBackground,
        allowInheritPrincipal: isJavaScriptURL,
        private: aPrivate,
        userContextId,
      });
      if (aWindow.updateTelemetry) {
        aWindow.updateTelemetry([aNode]);
      }
    }
  },

  /**
   * Helper for guessing scheme from an url string.
   * Used to avoid nsIURI overhead in frequently called UI functions. This is not
   * supposed be perfect, so use it only for UI purposes.
   *
   * @param {string} href The url to guess the scheme from.
   * @returns {string} guessed scheme for this url string.
   */
  guessUrlSchemeForUI(href) {
    return href.substr(0, href.indexOf(":"));
  },

  getBestTitle: function PUIU_getBestTitle(aNode, aDoNotCutTitle) {
    var title;
    if (!aNode.title && lazy.PlacesUtils.nodeIsURI(aNode)) {
      // if node title is empty, try to set the label using host and filename
      // Services.io.newURI will throw if aNode.uri is not a valid URI
      try {
        var uri = Services.io.newURI(aNode.uri);
        var host = uri.host;
        var fileName = uri.QueryInterface(Ci.nsIURL).fileName;
        // if fileName is empty, use path to distinguish labels
        if (aDoNotCutTitle) {
          title = host + uri.pathQueryRef;
        } else {
          title =
            host +
            (fileName
              ? (host ? "/" + this.ellipsis + "/" : "") + fileName
              : uri.pathQueryRef);
        }
      } catch (e) {
        // Use (no title) for non-standard URIs (data:, javascript:, ...)
        title = "";
      }
    } else {
      title = aNode.title;
    }

    return title || this.promptLocalization.formatValueSync("places-no-title");
  },

  shouldShowTabsFromOtherComputersMenuitem() {
    let weaveOK =
      lazy.Weave.Status.checkSetup() != lazy.CLIENT_NOT_CONFIGURED &&
      lazy.Weave.Svc.PrefBranch.getCharPref("firstSync", "") != "notReady";
    return weaveOK;
  },

  /**
   * WARNING TO ADDON AUTHORS: DO NOT USE THIS METHOD. IT'S LIKELY TO BE REMOVED IN A
   * FUTURE RELEASE.
   *
   * Checks if a place: href represents a folder shortcut.
   *
   * @param {string} queryString
   *        the query string to check (a place: href)
   * @returns {boolean} whether or not queryString represents a folder shortcut.
   * @throws if queryString is malformed.
   */
  isFolderShortcutQueryString(queryString) {
    // Based on GetSimpleBookmarksQueryFolder in nsNavHistory.cpp.

    let query = {},
      options = {};
    lazy.PlacesUtils.history.queryStringToQuery(queryString, query, options);
    query = query.value;
    options = options.value;
    return (
      query.folderCount == 1 &&
      !query.hasBeginTime &&
      !query.hasEndTime &&
      !query.hasDomain &&
      !query.hasURI &&
      !query.hasSearchTerms &&
      !query.tags.length == 0 &&
      options.maxResults == 0
    );
  },

  /**
   * Helpers for consumers of editBookmarkOverlay which don't have a node as their input.
   *
   * Given a bookmark object for either a url bookmark or a folder, returned by
   * Bookmarks.fetch (see Bookmark.jsm), this creates a node-like object suitable for
   * initialising the edit overlay with it.
   *
   * @param {object} aFetchInfo
   *        a bookmark object returned by Bookmarks.fetch.
   * @returns {object} a node-like object suitable for initialising editBookmarkOverlay.
   * @throws if aFetchInfo is representing a separator.
   */
  async promiseNodeLikeFromFetchInfo(aFetchInfo) {
    if (aFetchInfo.itemType == lazy.PlacesUtils.bookmarks.TYPE_SEPARATOR) {
      throw new Error("promiseNodeLike doesn't support separators");
    }

    let parent = {
      bookmarkGuid: aFetchInfo.parentGuid,
      type: Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER,
    };

    return Object.freeze({
      bookmarkGuid: aFetchInfo.guid,
      title: aFetchInfo.title,
      uri: aFetchInfo.url !== undefined ? aFetchInfo.url.href : "",

      get type() {
        if (aFetchInfo.itemType == lazy.PlacesUtils.bookmarks.TYPE_FOLDER) {
          return Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER;
        }

        if (!this.uri.length) {
          throw new Error("Unexpected item type");
        }

        if (/^place:/.test(this.uri)) {
          if (this.isFolderShortcutQueryString(this.uri)) {
            return Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT;
          }

          return Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY;
        }

        return Ci.nsINavHistoryResultNode.RESULT_TYPE_URI;
      },

      get parent() {
        return parent;
      },
    });
  },

  /**
   * This function wraps potentially large places transaction operations
   * with batch notifications to the result node, hence switching the views
   * to batch mode. If resultNode is not supplied, the function will
   * pass-through to functionToWrap.
   *
   * @param {nsINavHistoryResult} resultNode The result node to turn on batching.
   * @param {number} itemsBeingChanged The count of items being changed. If the
   *                                    count is lower than a threshold, then
   *                                    batching won't be set.
   * @param {Function} functionToWrap The function to
   * @returns {object} forwards the functionToWrap return value.
   */
  async batchUpdatesForNode(resultNode, itemsBeingChanged, functionToWrap) {
    if (!resultNode) {
      return functionToWrap();
    }

    if (itemsBeingChanged > ITEM_CHANGED_BATCH_NOTIFICATION_THRESHOLD) {
      resultNode.onBeginUpdateBatch();
    }

    try {
      return await functionToWrap();
    } finally {
      if (itemsBeingChanged > ITEM_CHANGED_BATCH_NOTIFICATION_THRESHOLD) {
        resultNode.onEndUpdateBatch();
      }
    }
  },

  /**
   * Processes a set of transfer items that have been dropped or pasted.
   * Batching will be applied where necessary.
   *
   * @param {Array} items A list of unwrapped nodes to process.
   * @param {object} insertionPoint The requested point for insertion.
   * @param {boolean} doCopy Set to true to copy the items, false will move them
   *                         if possible.
   * @param {object} view The view that should be used for batching.
   * @returns {Array} Returns an empty array when the insertion point is a tag, else
   *                 returns an array of copied or moved guids.
   */
  async handleTransferItems(items, insertionPoint, doCopy, view) {
    let transactions;
    let itemsCount;
    if (insertionPoint.isTag) {
      let urls = items.filter(item => "uri" in item).map(item => item.uri);
      itemsCount = urls.length;
      transactions = [
        lazy.PlacesTransactions.Tag({ urls, tag: insertionPoint.tagName }),
      ];
    } else {
      let insertionIndex = await insertionPoint.getIndex();
      itemsCount = items.length;
      transactions = getTransactionsForTransferItems(
        items,
        insertionIndex,
        insertionPoint.guid,
        !doCopy
      );
    }

    // Check if we actually have something to add, if we don't it probably wasn't
    // valid, or it was moving to the same location, so just ignore it.
    if (!transactions.length) {
      return [];
    }

    let guidsToSelect = await this.batchUpdatesForNode(
      getResultForBatching(view),
      itemsCount,
      async () =>
        lazy.PlacesTransactions.batch(transactions, "handleTransferItems")
    );

    // If we're inserting into a tag, we don't get the resulting guids.
    return insertionPoint.isTag ? [] : guidsToSelect.flat();
  },

  onSidebarTreeClick(event) {
    // right-clicks are not handled here
    if (event.button == 2) {
      return;
    }

    let tree = event.target.parentNode;
    let cell = tree.getCellAt(event.clientX, event.clientY);
    if (cell.row == -1 || cell.childElt == "twisty") {
      return;
    }

    // getCoordsForCellItem returns the x coordinate in logical coordinates
    // (i.e., starting from the left and right sides in LTR and RTL modes,
    // respectively.)  Therefore, we make sure to exclude the blank area
    // before the tree item icon (that is, to the left or right of it in
    // LTR and RTL modes, respectively) from the click target area.
    let win = tree.ownerGlobal;
    let rect = tree.getCoordsForCellItem(cell.row, cell.col, "image");
    let isRTL = win.getComputedStyle(tree).direction == "rtl";
    let mouseInGutter = isRTL ? event.clientX > rect.x : event.clientX < rect.x;

    let metaKey =
      AppConstants.platform === "macosx" ? event.metaKey : event.ctrlKey;
    let modifKey = metaKey || event.shiftKey;
    let isContainer = tree.view.isContainer(cell.row);
    let openInTabs =
      isContainer &&
      (event.button == 1 || (event.button == 0 && modifKey)) &&
      lazy.PlacesUtils.hasChildURIs(tree.view.nodeForTreeIndex(cell.row));

    if (event.button == 0 && isContainer && !openInTabs) {
      tree.view.toggleOpenState(cell.row);
    } else if (
      !mouseInGutter &&
      openInTabs &&
      event.originalTarget.localName == "treechildren"
    ) {
      tree.view.selection.select(cell.row);
      this.openMultipleLinksInTabs(tree.selectedNode, event, tree);
    } else if (
      !mouseInGutter &&
      !isContainer &&
      event.originalTarget.localName == "treechildren"
    ) {
      // Clear all other selection since we're loading a link now. We must
      // do this *before* attempting to load the link since openURL uses
      // selection as an indication of which link to load.
      tree.view.selection.select(cell.row);
      this.openNodeWithEvent(tree.selectedNode, event);
    }
  },

  onSidebarTreeKeyPress(event) {
    let node = event.target.selectedNode;
    if (node) {
      if (event.keyCode == event.DOM_VK_RETURN) {
        PlacesUIUtils.openNodeWithEvent(node, event);
      }
    }
  },

  /**
   * The following function displays the URL of a node that is being
   * hovered over.
   *
   * @param {object} event
   *   The event that triggered the hover.
   */
  onSidebarTreeMouseMove(event) {
    let treechildren = event.target;
    if (treechildren.localName != "treechildren") {
      return;
    }

    let tree = treechildren.parentNode;
    let cell = tree.getCellAt(event.clientX, event.clientY);

    // cell.row is -1 when the mouse is hovering an empty area within the tree.
    // To avoid showing a URL from a previously hovered node for a currently
    // hovered non-url node, we must clear the moused-over URL in these cases.
    if (cell.row != -1) {
      let node = tree.view.nodeForTreeIndex(cell.row);
      if (lazy.PlacesUtils.nodeIsURI(node)) {
        this.setMouseoverURL(node.uri, tree.ownerGlobal);
        return;
      }
    }
    this.setMouseoverURL("", tree.ownerGlobal);
  },

  setMouseoverURL(url, win) {
    // When the browser window is closed with an open sidebar, the sidebar
    // unload event happens after the browser's one.  In this case
    // top.XULBrowserWindow has been nullified already.
    if (win.top.XULBrowserWindow) {
      win.top.XULBrowserWindow.setOverLink(url);
    }
  },

  /**
   * Uncollapses PersonalToolbar if its collapsed status is not
   * persisted, and user customized it or changed default bookmarks.
   *
   * If the user does not have a persisted value for the toolbar's
   * "collapsed" attribute, try to determine whether it's customized.
   *
   * @param {boolean} aForceVisible Set to true to ignore if the user had
   * previously collapsed the toolbar manually.
   */
  NUM_TOOLBAR_BOOKMARKS_TO_UNHIDE: 3,
  async maybeToggleBookmarkToolbarVisibility(aForceVisible = false) {
    const BROWSER_DOCURL = AppConstants.BROWSER_CHROME_URL;
    let xulStore = Services.xulStore;

    if (
      aForceVisible ||
      !xulStore.hasValue(BROWSER_DOCURL, "PersonalToolbar", "collapsed")
    ) {
      function uncollapseToolbar() {
        Services.obs.notifyObservers(
          null,
          "browser-set-toolbar-visibility",
          JSON.stringify([lazy.CustomizableUI.AREA_BOOKMARKS, "true"])
        );
      }
      // We consider the toolbar customized if it has more than
      // NUM_TOOLBAR_BOOKMARKS_TO_UNHIDE children, or if it has a persisted
      // currentset value.
      let toolbarIsCustomized = xulStore.hasValue(
        BROWSER_DOCURL,
        "PersonalToolbar",
        "currentset"
      );
      if (aForceVisible || toolbarIsCustomized) {
        uncollapseToolbar();
        return;
      }

      let numBookmarksOnToolbar = (
        await lazy.PlacesUtils.bookmarks.fetch(
          lazy.PlacesUtils.bookmarks.toolbarGuid
        )
      ).childCount;
      if (numBookmarksOnToolbar > this.NUM_TOOLBAR_BOOKMARKS_TO_UNHIDE) {
        uncollapseToolbar();
      }
    }
  },

  async managedPlacesContextShowing(event) {
    let menupopup = event.target;
    let document = menupopup.ownerDocument;
    let window = menupopup.ownerGlobal;
    // We need to populate the submenus in order to have information
    // to show the context menu.
    if (
      menupopup.triggerNode.id == "managed-bookmarks" &&
      !menupopup.triggerNode.menupopup.hasAttribute("hasbeenopened")
    ) {
      await window.PlacesToolbarHelper.populateManagedBookmarks(
        menupopup.triggerNode.menupopup
      );
    }
    let linkItems = [
      "placesContext_open:newtab",
      "placesContext_open:newwindow",
      "placesContext_openSeparator",
      "placesContext_copy",
    ];
    // Hide everything. We'll unhide the things we need.
    Array.from(menupopup.children).forEach(function (child) {
      child.hidden = true;
    });
    // Store triggerNode in controller for checking if commands are enabled
    this.managedBookmarksController.triggerNode = menupopup.triggerNode;
    // Container in this context means a folder.
    let isFolder = menupopup.triggerNode.hasAttribute("container");
    if (isFolder) {
      // Disable the openContainerInTabs menuitem if there
      // are no children of the menu that have links.
      let openContainerInTabs_menuitem = document.getElementById(
        "placesContext_openContainer:tabs"
      );
      let menuitems = menupopup.triggerNode.menupopup.children;
      let openContainerInTabs = Array.from(menuitems).some(
        menuitem => menuitem.link
      );
      openContainerInTabs_menuitem.disabled = !openContainerInTabs;
      openContainerInTabs_menuitem.hidden = false;
    } else {
      linkItems.forEach(id => (document.getElementById(id).hidden = false));
      document.getElementById("placesContext_open:newprivatewindow").hidden =
        lazy.PrivateBrowsingUtils.isWindowPrivate(window) ||
        !lazy.PrivateBrowsingUtils.enabled;
      document.getElementById("placesContext_open:newcontainertab").hidden =
        !Services.prefs.getBoolPref("privacy.userContext.enabled", false);
    }

    event.target.ownerGlobal.updateCommands("places");
  },

  placesContextShowing(event) {
    let menupopup = event.target;
    if (menupopup.id != "placesContext") {
      // Ignore any popupshowing events from submenus
      return true;
    }

    PlacesUIUtils.lastContextMenuTriggerNode = menupopup.triggerNode;

    if (Services.prefs.getBoolPref("browser.tabs.loadBookmarksInTabs", false)) {
      menupopup.ownerDocument
        .getElementById("placesContext_open")
        .removeAttribute("default");
      menupopup.ownerDocument
        .getElementById("placesContext_open:newtab")
        .setAttribute("default", "true");
      // else clause ensures correct behavior if pref is repeatedly toggled
    } else {
      menupopup.ownerDocument
        .getElementById("placesContext_open:newtab")
        .removeAttribute("default");
      menupopup.ownerDocument
        .getElementById("placesContext_open")
        .setAttribute("default", "true");
    }

    let isManaged = !!menupopup.triggerNode.closest("#managed-bookmarks");
    if (isManaged) {
      this.managedPlacesContextShowing(event);
      return true;
    }
    menupopup._view = this.getViewForNode(menupopup.triggerNode);
    if (!menupopup._view) {
      // This can happen if we try to invoke the context menu on
      // an uninitialized places toolbar. Just bail out:
      event.preventDefault();
      return false;
    }
    if (!this.openInTabClosesMenu) {
      menupopup.ownerDocument
        .getElementById("placesContext_open:newtab")
        .setAttribute("closemenu", "single");
    }
    return menupopup._view.buildContextMenu(menupopup);
  },

  placesContextHiding(event) {
    let menupopup = event.target;
    if (menupopup._view) {
      menupopup._view.destroyContextMenu();
    }

    if (menupopup.id == "placesContext") {
      PlacesUIUtils.lastContextMenuTriggerNode = null;
    }
  },

  createContainerTabMenu(event) {
    let window = event.target.ownerGlobal;
    return window.createUserContextMenu(event, { isContextMenu: true });
  },

  openInContainerTab(event) {
    let userContextId = parseInt(
      event.target.getAttribute("data-usercontextid")
    );
    let triggerNode = this.lastContextMenuTriggerNode;
    let isManaged = !!triggerNode?.closest("#managed-bookmarks");
    if (isManaged) {
      let window = triggerNode.ownerGlobal;
      window.openTrustedLinkIn(triggerNode.link, "tab", { userContextId });
      return;
    }
    let view = this.getViewForNode(triggerNode);
    this._openNodeIn(view.selectedNode, "tab", view.ownerWindow, {
      userContextId,
    });
  },

  openSelectionInTabs(event) {
    let isManaged =
      !!event.target.parentNode.triggerNode.closest("#managed-bookmarks");
    let controller;
    if (isManaged) {
      controller = this.managedBookmarksController;
    } else {
      controller = PlacesUIUtils.getViewForNode(
        PlacesUIUtils.lastContextMenuTriggerNode
      ).controller;
    }
    controller.openSelectionInTabs(event);
  },

  managedBookmarksController: {
    triggerNode: null,

    openSelectionInTabs(event) {
      let window = event.target.ownerGlobal;
      let menuitems = event.target.parentNode.triggerNode.menupopup.children;
      let items = [];
      for (let i = 0; i < menuitems.length; i++) {
        if (menuitems[i].link) {
          let item = {};
          item.uri = menuitems[i].link;
          item.isBookmark = true;
          items.push(item);
        }
      }
      PlacesUIUtils.openTabset(items, event, window);
    },

    isCommandEnabled(command) {
      switch (command) {
        case "placesCmd_copy":
        case "placesCmd_open:window":
        case "placesCmd_open:privatewindow":
        case "placesCmd_open:tab": {
          return true;
        }
      }
      return false;
    },

    doCommand(command) {
      let window = this.triggerNode.ownerGlobal;
      switch (command) {
        case "placesCmd_copy":
          // This is a little hacky, but there is a lot of code in Places that handles
          // clipboard stuff, so it's easier to reuse.
          let node = {};
          node.type = 0;
          node.title = this.triggerNode.label;
          node.uri = this.triggerNode.link;

          // Copied from _populateClipboard in controller.js

          // This order is _important_! It controls how this and other applications
          // select data to be inserted based on type.
          let contents = [
            { type: lazy.PlacesUtils.TYPE_X_MOZ_URL, entries: [] },
            { type: lazy.PlacesUtils.TYPE_HTML, entries: [] },
            { type: lazy.PlacesUtils.TYPE_PLAINTEXT, entries: [] },
          ];

          contents.forEach(function (content) {
            content.entries.push(lazy.PlacesUtils.wrapNode(node, content.type));
          });

          let xferable = Cc[
            "@mozilla.org/widget/transferable;1"
          ].createInstance(Ci.nsITransferable);
          xferable.init(null);

          function addData(type, data) {
            xferable.addDataFlavor(type);
            xferable.setTransferData(
              type,
              lazy.PlacesUtils.toISupportsString(data)
            );
          }

          contents.forEach(function (content) {
            addData(content.type, content.entries.join(lazy.PlacesUtils.endl));
          });

          Services.clipboard.setData(
            xferable,
            null,
            Ci.nsIClipboard.kGlobalClipboard
          );
          break;
        case "placesCmd_open:privatewindow":
          window.openTrustedLinkIn(this.triggerNode.link, "window", {
            private: true,
          });
          break;
        case "placesCmd_open:window":
          window.openTrustedLinkIn(this.triggerNode.link, "window", {
            private: false,
          });
          break;
        case "placesCmd_open:tab": {
          window.openTrustedLinkIn(this.triggerNode.link, "tab");
        }
      }
    },
  },

  async maybeAddImportButton() {
    if (!Services.policies.isAllowed("profileImport")) {
      return;
    }

    let numberOfBookmarks = await lazy.PlacesUtils.withConnectionWrapper(
      "PlacesUIUtils: maybeAddImportButton",
      async db => {
        let rows = await db.execute(
          `SELECT COUNT(*) as n FROM moz_bookmarks b
           JOIN moz_bookmarks p ON p.id = b.parent
           WHERE p.guid = :guid`,
          { guid: lazy.PlacesUtils.bookmarks.toolbarGuid }
        );
        return rows[0].getResultByName("n");
      }
    ).catch(e => {
      // We want to report errors, but we still want to add the button then:
      console.error(e);
      return 0;
    });

    if (numberOfBookmarks < 3) {
      lazy.CustomizableUI.addWidgetToArea(
        "import-button",
        lazy.CustomizableUI.AREA_BOOKMARKS,
        0
      );
      Services.prefs.setBoolPref("browser.bookmarks.addedImportButton", true);
      this.removeImportButtonWhenImportSucceeds();
    }
  },

  removeImportButtonWhenImportSucceeds() {
    // If the user (re)moved the button, clear the pref and stop worrying about
    // moving the item.
    let placement = lazy.CustomizableUI.getPlacementOfWidget("import-button");
    if (placement?.area != lazy.CustomizableUI.AREA_BOOKMARKS) {
      Services.prefs.clearUserPref("browser.bookmarks.addedImportButton");
      return;
    }
    // Otherwise, wait for a successful migration:
    let obs = (subject, topic, data) => {
      if (
        data == lazy.MigrationUtils.resourceTypes.BOOKMARKS &&
        lazy.MigrationUtils.getImportedCount("bookmarks") > 0
      ) {
        lazy.CustomizableUI.removeWidgetFromArea("import-button");
        Services.prefs.clearUserPref("browser.bookmarks.addedImportButton");
        Services.obs.removeObserver(obs, "Migration:ItemAfterMigrate");
        Services.obs.removeObserver(obs, "Migration:ItemError");
      }
    };
    Services.obs.addObserver(obs, "Migration:ItemAfterMigrate");
    Services.obs.addObserver(obs, "Migration:ItemError");
  },

  /**
   * Tries to initiate a speculative connection to a given url. This is not
   * infallible, if a speculative connection cannot be initialized, it will be a
   * no-op.
   *
   * @param {nsIURI|URL|string} url entity to initiate
   *        a speculative connection for.
   * @param {window} window the window from where the connection is initialized.
   */
  setupSpeculativeConnection(url, window) {
    if (
      !Services.prefs.getBoolPref(
        "browser.places.speculativeConnect.enabled",
        true
      )
    ) {
      return;
    }
    if (!url.startsWith("http")) {
      return;
    }
    try {
      let uri = url instanceof Ci.nsIURI ? url : Services.io.newURI(url);
      Services.io.speculativeConnect(
        uri,
        window.gBrowser.contentPrincipal,
        null,
        false
      );
    } catch (ex) {
      // Can't setup speculative connection for this url, just ignore it.
    }
  },

  /**
   * Generates a cached-favicon: link for an icon URL, that will allow to fetch
   * the icon from the local favicons cache, rather than from the network.
   * If the icon URL is invalid, fallbacks to the default favicon URL.
   *
   * @param {string} icon The url of the icon to load from local cache.
   * @returns {string} a "cached-favicon:" prefixed URL, unless the original
   *   URL protocol refers to a local resource, then it will just pass-through
   *   unchanged.
   */
  getImageURL(icon) {
    // don't initiate a connection just to fetch a favicon (see bug 467828)
    try {
      return lazy.PlacesUtils.favicons.getFaviconLinkForIcon(
        Services.io.newURI(icon)
      ).spec;
    } catch (ex) {}
    return lazy.PlacesUtils.favicons.defaultFavicon.spec;
  },

  /**
   * Determines the string indexes where titles differ from similar titles (where
   * the first n characters are the same) in the provided list of items, and
   * adds that into the item.
   *
   * This assumes the titles will be displayed along the lines of
   * `Start of title ... place where differs` the index would be reference
   * the `p` here.
   *
   * @param {object[]} candidates
   *   An array of candidates to modify. The candidates should have a `title`
   *   property which should be a string or null.
   *   The order of the array does not matter. The objects are modified
   *   in-place.
   *   If a difference to other similar titles is found then a
   *   `titleDifferentIndex` property will be inserted into all similar
   *   candidates with the index of the start of the difference.
   */
  insertTitleStartDiffs(candidates) {
    function findStartDifference(a, b) {
      let i;
      // We already know the start is the same, so skip that part.
      for (i = PlacesUIUtils.similarTitlesMinChars; i < a.length; i++) {
        if (a[i] != b[i]) {
          return i;
        }
      }
      if (b.length > i) {
        return i;
      }
      // They are the same.
      return -1;
    }

    let longTitles = new Map();

    for (let candidate of candidates) {
      // Title is too short for us to care about, simply continue.
      if (
        !candidate.title ||
        candidate.title.length < this.similarTitlesMinChars
      ) {
        continue;
      }
      let titleBeginning = candidate.title.slice(0, this.similarTitlesMinChars);
      let matches = longTitles.get(titleBeginning);
      if (matches) {
        for (let match of matches) {
          let startDiff = findStartDifference(candidate.title, match.title);
          if (startDiff > 0) {
            candidate.titleDifferentIndex = startDiff;
            // If we have an existing difference index for the match, move
            // it forward if this one is earlier in the string.
            if (
              !("titleDifferentIndex" in match) ||
              match.titleDifferentIndex > startDiff
            ) {
              match.titleDifferentIndex = startDiff;
            }
          }
        }

        matches.push(candidate);
      } else {
        longTitles.set(titleBeginning, [candidate]);
      }
    }
  },
};

/**
 * Promise used by the toolbar view browser-places to determine whether we
 * can start loading its content (which involves IO, and so is postponed
 * during startup).
 */
PlacesUIUtils.canLoadToolbarContentPromise = new Promise(resolve => {
  PlacesUIUtils.unblockToolbars = resolve;
});

// These are lazy getters to avoid importing PlacesUtils immediately.
ChromeUtils.defineLazyGetter(PlacesUIUtils, "PLACES_FLAVORS", () => {
  return [
    lazy.PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER,
    lazy.PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR,
    lazy.PlacesUtils.TYPE_X_MOZ_PLACE,
  ];
});
ChromeUtils.defineLazyGetter(PlacesUIUtils, "URI_FLAVORS", () => {
  return [
    lazy.PlacesUtils.TYPE_X_MOZ_URL,
    TAB_DROP_TYPE,
    lazy.PlacesUtils.TYPE_PLAINTEXT,
  ];
});
ChromeUtils.defineLazyGetter(PlacesUIUtils, "SUPPORTED_FLAVORS", () => {
  return [...PlacesUIUtils.PLACES_FLAVORS, ...PlacesUIUtils.URI_FLAVORS];
});

ChromeUtils.defineLazyGetter(PlacesUIUtils, "ellipsis", function () {
  return Services.prefs.getComplexValue(
    "intl.ellipsis",
    Ci.nsIPrefLocalizedString
  ).data;
});

ChromeUtils.defineLazyGetter(PlacesUIUtils, "promptLocalization", () => {
  return new Localization(
    ["browser/placesPrompts.ftl", "branding/brand.ftl"],
    true
  );
});

XPCOMUtils.defineLazyPreferenceGetter(
  PlacesUIUtils,
  "similarTitlesMinChars",
  "browser.places.similarTitlesMinChars",
  20
);
XPCOMUtils.defineLazyPreferenceGetter(
  PlacesUIUtils,
  "loadBookmarksInBackground",
  "browser.tabs.loadBookmarksInBackground",
  false
);
XPCOMUtils.defineLazyPreferenceGetter(
  PlacesUIUtils,
  "loadBookmarksInTabs",
  "browser.tabs.loadBookmarksInTabs",
  false
);
XPCOMUtils.defineLazyPreferenceGetter(
  PlacesUIUtils,
  "openInTabClosesMenu",
  "browser.bookmarks.openInTabClosesMenu",
  false
);
XPCOMUtils.defineLazyPreferenceGetter(
  PlacesUIUtils,
  "maxRecentFolders",
  "browser.bookmarks.editDialog.maxRecentFolders",
  7
);

XPCOMUtils.defineLazyPreferenceGetter(
  PlacesUIUtils,
  "defaultParentGuid",
  "browser.bookmarks.defaultLocation",
  "", // Avoid eagerly loading PlacesUtils.
  null,
  async prefValue => {
    if (!prefValue) {
      return lazy.PlacesUtils.bookmarks.toolbarGuid;
    }
    if (["toolbar", "menu", "unfiled"].includes(prefValue)) {
      return lazy.PlacesUtils.bookmarks[prefValue + "Guid"];
    }

    try {
      return await lazy.PlacesUtils.bookmarks
        .fetch({ guid: prefValue })
        .then(bm => bm.guid);
    } catch (ex) {
      // The guid may have an invalid format.
      return lazy.PlacesUtils.bookmarks.toolbarGuid;
    }
  }
);

/**
 * Determines if an unwrapped node can be moved.
 *
 * @param {object} unwrappedNode
 *        A node unwrapped by PlacesUtils.unwrapNodes().
 * @returns {boolean} True if the node can be moved, false otherwise.
 */
function canMoveUnwrappedNode(unwrappedNode) {
  if (
    (unwrappedNode.concreteGuid &&
      lazy.PlacesUtils.isRootItem(unwrappedNode.concreteGuid)) ||
    (unwrappedNode.guid && lazy.PlacesUtils.isRootItem(unwrappedNode.guid))
  ) {
    return false;
  }

  let parentGuid = unwrappedNode.parentGuid;
  if (parentGuid == lazy.PlacesUtils.bookmarks.rootGuid) {
    return false;
  }

  return true;
}

/**
 * This gets the most appropriate item for using for batching. In the case of multiple
 * views being related, the method returns the most expensive result to batch.
 * For example, if it detects the left-hand library pane, then it will look for
 * and return the reference to the right-hand pane.
 *
 * @param {object} viewOrElement The item to check.
 * @returns {object} Will return the best result node to batch, or null
 *                  if one could not be found.
 */
function getResultForBatching(viewOrElement) {
  if (
    viewOrElement &&
    Element.isInstance(viewOrElement) &&
    viewOrElement.id === "placesList"
  ) {
    // Note: fall back to the existing item if we can't find the right-hane pane.
    viewOrElement =
      viewOrElement.ownerDocument.getElementById("placeContent") ||
      viewOrElement;
  }

  if (viewOrElement && viewOrElement.result) {
    return viewOrElement.result;
  }

  return null;
}

/**
 * Processes a set of transfer items and returns transactions to insert or
 * move them.
 *
 * @param {Array} items A list of unwrapped nodes to get transactions for.
 * @param {number} insertionIndex The requested index for insertion.
 * @param {string} insertionParentGuid The guid of the parent folder to insert
 *                                     or move the items to.
 * @param {boolean} doMove Set to true to MOVE the items if possible, false will
 *                         copy them.
 * @returns {Array} Returns an array of created PlacesTransactions.
 */
function getTransactionsForTransferItems(
  items,
  insertionIndex,
  insertionParentGuid,
  doMove
) {
  let canMove = true;
  for (let item of items) {
    if (!PlacesUIUtils.SUPPORTED_FLAVORS.includes(item.type)) {
      throw new Error(`Unsupported '${item.type}' data type`);
    }

    // Work out if this is data from the same app session we're running in.
    if (
      !("instanceId" in item) ||
      item.instanceId != lazy.PlacesUtils.instanceId
    ) {
      if (item.type == lazy.PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER) {
        throw new Error(
          "Can't copy a container from a legacy-transactions build"
        );
      }
      // Only log if this is one of "our" types as external items, e.g. drag from
      // url bar to toolbar, shouldn't complain.
      if (PlacesUIUtils.PLACES_FLAVORS.includes(item.type)) {
        console.error(
          "Tried to move an unmovable Places " +
            "node, reverting to a copy operation."
        );
      }

      // We can never move from an external copy.
      canMove = false;
    }

    if (doMove && canMove) {
      canMove = canMoveUnwrappedNode(item);
    }
  }

  if (doMove && !canMove) {
    doMove = false;
  }

  if (doMove) {
    // Move is simple, we pass the transaction a list of GUIDs and where to move
    // them to.
    return [
      lazy.PlacesTransactions.Move({
        guids: items.map(item => item.itemGuid),
        newParentGuid: insertionParentGuid,
        newIndex: insertionIndex,
      }),
    ];
  }

  return getTransactionsForCopy(items, insertionIndex, insertionParentGuid);
}

/**
 * Processes a set of transfer items and returns an array of transactions.
 *
 * @param {Array} items A list of unwrapped nodes to get transactions for.
 * @param {number} insertionIndex The requested index for insertion.
 * @param {string} insertionParentGuid The guid of the parent folder to insert
 *                                     or move the items to.
 * @returns {Array} Returns an array of created PlacesTransactions.
 */
function getTransactionsForCopy(items, insertionIndex, insertionParentGuid) {
  let transactions = [];
  let index = insertionIndex;

  for (let item of items) {
    let transaction;
    let guid = item.itemGuid;

    if (
      PlacesUIUtils.PLACES_FLAVORS.includes(item.type) &&
      // For anything that is comming from within this session, we do a
      // direct copy, otherwise we fallback and form a new item below.
      "instanceId" in item &&
      item.instanceId == lazy.PlacesUtils.instanceId &&
      // If the Item doesn't have a guid, this could be a virtual tag query or
      // other item, so fallback to inserting a new bookmark with the URI.
      guid &&
      // For virtual root items, we fallback to creating a new bookmark, as
      // we want a shortcut to be created, not a full tree copy.
      !lazy.PlacesUtils.bookmarks.isVirtualRootItem(guid) &&
      !lazy.PlacesUtils.isVirtualLeftPaneItem(guid)
    ) {
      transaction = lazy.PlacesTransactions.Copy({
        guid,
        newIndex: index,
        newParentGuid: insertionParentGuid,
      });
    } else if (item.type == lazy.PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR) {
      transaction = lazy.PlacesTransactions.NewSeparator({
        index,
        parentGuid: insertionParentGuid,
      });
    } else {
      let title =
        item.type != lazy.PlacesUtils.TYPE_PLAINTEXT ? item.title : item.uri;
      transaction = lazy.PlacesTransactions.NewBookmark({
        index,
        parentGuid: insertionParentGuid,
        title,
        url: item.uri,
      });
    }

    transactions.push(transaction);

    if (index != -1) {
      index++;
    }
  }
  return transactions;
}

function getBrowserWindow(aWindow) {
  // Prefer the caller window if it's a browser window, otherwise use
  // the top browser window.
  return aWindow &&
    aWindow.document.documentElement.getAttribute("windowtype") ==
      "navigator:browser"
    ? aWindow
    : lazy.BrowserWindowTracker.getTopWindow();
}