Codebase list gnome-shell-extension-appindicator / v50 appIndicator.js
v50

Tree @v50 (Download .tar.gz)

appIndicator.js @v50raw · history · blame

   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
// This file is part of the AppIndicator/KStatusNotifierItem GNOME Shell extension
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

/* exported AppIndicatorProxy, AppIndicator IconActor */

const Clutter = imports.gi.Clutter;
const GdkPixbuf = imports.gi.GdkPixbuf;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Gdk = imports.gi.Gdk;
const Gtk = imports.gi.Gtk;
const Meta = imports.gi.Meta;
const St = imports.gi.St;

const Extension = imports.misc.extensionUtils.getCurrentExtension();
const Signals = imports.signals;

const IconCache = Extension.imports.iconCache;
const Util = Extension.imports.util;
const Interfaces = Extension.imports.interfaces;
const Params = imports.misc.params;
const PixmapsUtils = Extension.imports.pixmapsUtils;
const PromiseUtils = Extension.imports.promiseUtils;
const SettingsManager = Extension.imports.settingsManager;

PromiseUtils._promisify(Gio.File.prototype, 'read_async', 'read_finish');
PromiseUtils._promisify(Gio._LocalFilePrototype, 'read_async', 'read_finish');
PromiseUtils._promisify(GdkPixbuf.Pixbuf, 'get_file_info_async', 'get_file_info_finish');
PromiseUtils._promisify(GdkPixbuf.Pixbuf, 'new_from_stream_at_scale_async', 'new_from_stream_finish');
PromiseUtils._promisify(Gio.DBusProxy.prototype, 'init_async', 'init_finish');

if (St.IconInfo)
    PromiseUtils._promisify(St.IconInfo.prototype, 'load_symbolic_async', 'load_symbolic_finish');
else
    PromiseUtils._promisify(Gtk.IconInfo.prototype, 'load_symbolic_async', 'load_symbolic_finish');

const MAX_UPDATE_FREQUENCY = 100; // In ms

// eslint-disable-next-line no-unused-vars
const SNICategory = Object.freeze({
    APPLICATION: 'ApplicationStatus',
    COMMUNICATIONS: 'Communications',
    SYSTEM: 'SystemServices',
    HARDWARE: 'Hardware',
});

var SNIStatus = Object.freeze({
    PASSIVE: 'Passive',
    ACTIVE: 'Active',
    NEEDS_ATTENTION: 'NeedsAttention',
});

const SNIconType = Object.freeze({
    NORMAL: 0,
    ATTENTION: 1,
    OVERLAY: 2,

    toPropertyName: (iconType, params = { isPixbuf: false }) => {
        let propertyName = 'Icon';

        if (iconType === SNIconType.OVERLAY)
            propertyName = 'OverlayIcon';
        else if (iconType === SNIconType.ATTENTION)
            propertyName = 'AttentionIcon';

        return `${propertyName}${params.isPixbuf ? 'Pixmap' : 'Name'}`;
    },
});

var AppIndicatorProxy = GObject.registerClass({
    Signals: { 'destroy': {} },
}, class AppIndicatorProxy extends Gio.DBusProxy {
    static get interfaceInfo() {
        if (!this._interfaceInfo) {
            this._interfaceInfo = Gio.DBusInterfaceInfo.new_for_xml(
                Interfaces.StatusNotifierItem);
        }
        return this._interfaceInfo;
    }

    static get OPTIONAL_PROPERTIES() {
        return [
            'XAyatanaLabel',
            'XAyatanaLabelGuide',
            'XAyatanaOrderingIndex',
            'IconAccessibleDesc',
            'AttentionAccessibleDesc',
        ];
    }

    static get TUPLE_TYPE() {
        if (!this._tupleType)
            this._tupleType = new GLib.VariantType('()');

        return this._tupleType;
    }

    static get TUPLE_VARIANT_TYPE() {
        if (!this._tupleVariantType)
            this._tupleVariantType = new GLib.VariantType('(v)');

        return this._tupleVariantType;
    }

    static destroy() {
        delete this._interfaceInfo;
        delete this._tupleVariantType;
        delete this._tupleType;
    }

    _init(busName, objectPath) {
        const { interfaceInfo } = AppIndicatorProxy;

        super._init({
            g_connection: Gio.DBus.session,
            g_interface_name: interfaceInfo.name,
            g_interface_info: interfaceInfo,
            g_name: busName,
            g_object_path: objectPath,
            g_flags: Gio.DBusProxyFlags.GET_INVALIDATED_PROPERTIES,
        });

        this.set_cached_property('Status',
            new GLib.Variant('s', SNIStatus.PASSIVE));

        this._signalIds = [];
        this._accumulatedProperties = new Set();
        this._cancellables = new Map();
        this._changedProperties = Object.create(null);

        this._signalIds.push(this.connect('g-signal',
            (_proxy, ...args) => this._onSignal(...args).catch(logError)));

        this._signalIds.push(this.connect('notify::g-name-owner', () => {
            this._resetNeededProperties();
            if (!this.gNameOwner)
                this._cancelRefreshProperties();
            else
                this._setupProxyPropertyList();
        }));
    }

    async initAsync(cancellable) {
        cancellable = new Util.CancellableChild(cancellable);
        await this.init_async(GLib.PRIORITY_DEFAULT, cancellable);
        this._cancellable = cancellable;

        this.gInterfaceInfo.methods.map(m => m.name).forEach(method =>
            this._ensureAsyncMethod(method));

        this._setupProxyPropertyList();
    }

    destroy() {
        this.emit('destroy');
        this._signalIds.forEach(id => this.disconnect(id));

        const cachedProperties = this.get_cached_property_names();
        if (cachedProperties) {
            cachedProperties.forEach(propertyName =>
                this.set_cached_property(propertyName, null));
        }

        if (this._cancellable)
            this._cancellable.cancel();

        this._cancellables.clear();
    }

    _setupProxyPropertyList() {
        this._propertiesList =
            (this.get_cached_property_names() || []).filter(p =>
                this.gInterfaceInfo.properties.some(pInfo => pInfo.name === p));

        if (this._propertiesList.length) {
            AppIndicatorProxy.OPTIONAL_PROPERTIES.forEach(
                p => this._addExtraProperty(p));
        }
    }

    _addExtraProperty(name) {
        if (this._propertiesList.includes(name))
            return;

        if (!(name in this)) {
            Object.defineProperty(this, name, {
                configurable: false,
                enumerable: true,
                get: () => {
                    const v = this.get_cached_property(name);
                    return v ? v.deep_unpack() : null;
                },
            });
        }

        this._propertiesList.push(name);
    }

    _signalToPropertyName(signal) {
        if (signal.startsWith('New'))
            return signal.substr(3);
        else if (signal.startsWith('XAyatanaNew'))
            return `XAyatana${signal.substr(11)}`;

        return null;
    }

    // The Author of the spec didn't like the PropertiesChanged signal, so he invented his own
    async _refreshOwnProperties(prop) {
        await Promise.all(
            [prop, `${prop}Name`, `${prop}Pixmap`, `${prop}AccessibleDesc`].filter(p =>
                this._propertiesList.includes(p)).map(async p => {
                try {
                    await this.refreshProperty(p, {
                        skipEqualityCheck: p.endsWith('Pixmap'),
                    });
                } catch (e) {
                    if (!AppIndicatorProxy.OPTIONAL_PROPERTIES.includes(p) ||
                        !e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_PROPERTY))
                        logError(e);
                }
            }));
    }

    async _onSignal(_sender, signal, params) {
        const property = this._signalToPropertyName(signal);
        if (!property)
            return;

        if (this.status === SNIStatus.PASSIVE &&
            ![...AppIndicator.NEEDED_PROPERTIES, 'Status'].includes(property)) {
            this._accumulatedProperties.add(property);
            return;
        }

        if (!params.get_type().equal(AppIndicatorProxy.TUPLE_TYPE)) {
            // If the property includes arguments, we can just queue the signal emission
            const [value] = params.unpack();
            try {
                await this._queuePropertyUpdate(property, value);
            } catch (e) {
                if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                    throw e;
            }

            if (!this._accumulatedProperties.size)
                return;
        } else {
            this._accumulatedProperties.add(property);
        }

        if (this._signalsAccumulator)
            return;

        this._signalsAccumulator = new PromiseUtils.TimeoutPromise(
            GLib.PRIORITY_DEFAULT_IDLE, MAX_UPDATE_FREQUENCY, this._cancellable);
        try {
            await this._signalsAccumulator;
            const refreshPropertiesPromises =
                [...this._accumulatedProperties].map(p =>
                    this._refreshOwnProperties(p));
            this._accumulatedProperties.clear();
            await Promise.all(refreshPropertiesPromises);
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                throw e;
        } finally {
            delete this._signalsAccumulator;
        }
    }

    _resetNeededProperties() {
        AppIndicator.NEEDED_PROPERTIES.forEach(p =>
            this.set_cached_property(p, null));
    }

    // This can be removed when we will have GNOME 43 as minimum version
    _ensureAsyncMethod(method) {
        if (this[`${method}Async`])
            return;

        if (!this[`${method}Remote`])
            throw new Error(`Missing remote method '${method}'`);

        this[`${method}Async`] = function (...args) {
            return new Promise((resolve, reject) => {
                this[`${method}Remote`](...args, (ret, e) => {
                    if (e)
                        reject(e);
                    else
                        resolve(ret);
                });
            });
        };
    }

    getProperty(propertyName, cancellable) {
        return this.g_connection.call(this.g_name,
            this.g_object_path, 'org.freedesktop.DBus.Properties', 'Get',
            GLib.Variant.new('(ss)', [this.g_interface_name, propertyName]),
            AppIndicatorProxy.TUPLE_VARIANT_TYPE, Gio.DBusCallFlags.NONE, -1,
            cancellable);
    }

    getProperties(cancellable) {
        return this.g_connection.call(this.g_name,
            this.g_object_path, 'org.freedesktop.DBus.Properties', 'GetAll',
            GLib.Variant.new('(s)', [this.g_interface_name]),
            GLib.VariantType.new('(a{sv})'), Gio.DBusCallFlags.NONE, -1,
            cancellable);
    }

    async refreshAllProperties() {
        const cancellableName = 'org.freedesktop.DBus.Properties.GetAll';
        const cancellable = this._cancelRefreshProperties({
            propertyName: cancellableName,
            addNew: true,
        });

        try {
            const [valuesVariant] = (await this.getProperties(
                cancellable)).deep_unpack();

            this._cancellables.delete(cancellableName);

            await Promise.all(
                Object.entries(valuesVariant).map(([propertyName, valueVariant]) =>
                    this._queuePropertyUpdate(propertyName, valueVariant, {
                        skipEqualityCheck: true,
                        cancellable,
                    })));
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
                // the property may not even exist, silently ignore it
                Util.Logger.debug(`While refreshing all properties: ${e}`);

                this.get_cached_property_names().forEach(propertyName =>
                    this.set_cached_property(propertyName, null));

                this._cancellables.delete(cancellableName);
                throw e;
            }
        }
    }

    async refreshProperty(propertyName, params) {
        params = Params.parse(params, {
            skipEqualityCheck: false,
        });

        const cancellable = this._cancelRefreshProperties({
            propertyName,
            addNew: true,
        });

        try {
            const [valueVariant] = (await this.getProperty(
                propertyName, cancellable)).deep_unpack();

            this._cancellables.delete(propertyName);
            await this._queuePropertyUpdate(propertyName, valueVariant,
                Object.assign(params, { cancellable }));
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
                // the property may not even exist, silently ignore it
                Util.Logger.debug(`While refreshing property ${propertyName}: ${e}`);
                this.set_cached_property(propertyName, null);
                this._cancellables.delete(propertyName);
                delete this._changedProperties[propertyName];
                throw e;
            }
        }
    }

    async _queuePropertyUpdate(propertyName, value, params) {
        params = Params.parse(params, {
            skipEqualityCheck: false,
            cancellable: null,
        });

        if (!params.skipEqualityCheck) {
            const cachedProperty = this.get_cached_property(propertyName);

            if (value && cachedProperty &&
                value.equal(this.get_cached_property(propertyName)))
                return;
        }

        this.set_cached_property(propertyName, value);

        // synthesize a batched property changed event
        this._changedProperties[propertyName] = value;

        if (!this._propertiesEmitTimeout || !this._propertiesEmitTimeout.pending()) {
            if (!params.cancellable) {
                params.cancellable = this._cancelRefreshProperties({
                    propertyName,
                    addNew: true,
                });
            }
            this._propertiesEmitTimeout = new PromiseUtils.TimeoutPromise(16,
                GLib.PRIORITY_DEFAULT_IDLE, params.cancellable);
            await this._propertiesEmitTimeout;

            if (Object.keys(this._changedProperties).length) {
                this.emit('g-properties-changed', GLib.Variant.new('a{sv}',
                    this._changedProperties), []);
                this._changedProperties = Object.create(null);
            }
        }
    }

    _cancelRefreshProperties(params) {
        params = Params.parse(params, {
            propertyName: undefined,
            addNew: false,
        });

        if (!this._cancellables.size && !params.addNew)
            return null;

        if (params.propertyName !== undefined) {
            let cancellable = this._cancellables.get(params.propertyName);
            if (cancellable) {
                cancellable.cancel();

                if (!params.addNew)
                    this._cancellables.delete(params.propertyName);
            }

            if (params.addNew) {
                cancellable = new Util.CancellableChild(this._cancellable);
                this._cancellables.set(params.propertyName, cancellable);
                return cancellable;
            }
        } else {
            this._cancellables.forEach(c => c.cancel());
            this._cancellables.clear();
            this._changedProperties = Object.create(null);
        }

        return null;
    }
});

if (imports.system.version < 17101) {
    /* In old versions wrappers are not applied to sub-classes, so let's do it */
    AppIndicatorProxy.prototype.init_async = Gio.DBusProxy.prototype.init_async;
}

/**
 * the AppIndicator class serves as a generic container for indicator information and functions common
 * for every displaying implementation (IndicatorMessageSource and IndicatorStatusIcon)
 */
var AppIndicator = class AppIndicatorsAppIndicator {

    static get NEEDED_PROPERTIES() {
        return ['Id', 'Menu'];
    }

    constructor(service, busName, object) {
        this.isReady = false;
        this.busName = busName;
        this._uniqueId = Util.indicatorId(service, busName, object);

        this._cancellable = new Gio.Cancellable();
        this._proxy = new AppIndicatorProxy(busName, object);
        this._invalidatedPixmapsIcons = new Set();

        this._setupProxy().catch(logError);
        Util.connectSmart(this._proxy, 'g-properties-changed', this, this._onPropertiesChanged);
        Util.connectSmart(this._proxy, 'notify::g-name-owner', this, this._nameOwnerChanged);

        if (this.uniqueId === service) {
            this._nameWatcher = new Util.NameWatcher(service);
            Util.connectSmart(this._nameWatcher, 'changed', this, this._nameOwnerChanged);
        }
    }

    async _setupProxy() {
        const cancellable = this._cancellable;

        try {
            await this._proxy.initAsync(cancellable);
            this._checkIfReady();
            await this._checkNeededProperties();
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
                logError(e, `While initalizing proxy for ${this._uniqueId}`);
                this.destroy();
            }
        }

        try {
            this._commandLine = await Util.getProcessName(this.busName,
                cancellable, GLib.PRIORITY_LOW);
        } catch (e) {
            Util.Logger.debug(`${this.uniqueId}, failed getting command line: ${e.message}`);
        }
    }

    _checkIfReady() {
        let wasReady = this.isReady;
        let isReady = false;

        if (this.hasNameOwner && this.id && this.menuPath)
            isReady = true;

        this.isReady = isReady;

        if (this.isReady && !wasReady) {
            if (this._delayCheck) {
                this._delayCheck.cancel();
                delete this._delayCheck;
            }

            this.emit('ready');
            return true;
        }

        return false;
    }

    async _checkNeededProperties() {
        if (this.id && this.menuPath)
            return true;

        const MAX_RETRIES = 3;
        const cancellable = this._cancellable;
        for (let checks = 0; checks < MAX_RETRIES; ++checks) {
            this._delayCheck = new PromiseUtils.TimeoutSecondsPromise(1,
                GLib.PRIORITY_DEFAULT_IDLE, cancellable);
            // eslint-disable-next-line no-await-in-loop
            await this._delayCheck;

            try {
                // eslint-disable-next-line no-await-in-loop
                await Promise.all(AppIndicator.NEEDED_PROPERTIES.map(p =>
                    this._proxy.refreshProperty(p)));
            } catch (e) {
                if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                    throw e;

                if (checks < MAX_RETRIES - 1)
                    continue;

                throw e;
            }

            if (this.id && this.menuPath)
                break;
        }

        return this.id && this.menuPath;
    }

    async _nameOwnerChanged() {
        if (!this.hasNameOwner) {
            this._checkIfReady();
        } else {
            try {
                await this._checkNeededProperties();
            } catch (e) {
                if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
                    Util.Logger.warn(`${this.uniqueId}, Impossible to get basic properties: ${e}`);
                    this.checkAlive();
                }
            }
        }

        this.emit('name-owner-changed');
    }

    // public property getters
    get title() {
        return this._proxy.Title;
    }

    get id() {
        return this._proxy.Id;
    }

    get uniqueId() {
        return this._uniqueId;
    }

    get status() {
        return this._proxy.Status;
    }

    get label() {
        return this._proxy.XAyatanaLabel || null;
    }

    get accessibleName() {
        const accessibleDesc = this.status === SNIStatus.NEEDS_ATTENTION
            ? this._proxy.AccessibleDesc : this._proxy.IconAccessibleDesc;

        return accessibleDesc || this.title;
    }

    get menuPath() {
        if (this._proxy.Menu === '/NO_DBUSMENU')
            return null;

        return this._proxy.Menu;
    }

    get attentionIcon() {
        return {
            theme: this._proxy.IconThemePath,
            name: this._proxy.AttentionIconName,
            pixmap: this._getPixmapProperty(SNIconType.ATTENTION),
        };
    }

    get icon() {
        return {
            theme: this._proxy.IconThemePath,
            name: this._proxy.IconName,
            pixmap: this._getPixmapProperty(SNIconType.NORMAL),
        };
    }

    get overlayIcon() {
        return {
            theme: this._proxy.IconThemePath,
            name: this._proxy.OverlayIconName,
            pixmap: this._getPixmapProperty(SNIconType.OVERLAY),
        };
    }

    get hasNameOwner() {
        if (this._nameWatcher && !this._nameWatcher.nameOnBus)
            return false;
        return !!this._proxy.g_name_owner;
    }

    get cancellable() {
        return this._cancellable;
    }

    async checkAlive() {
        // Some applications (hey electron!) just remove the indicator object
        // from bus after hiding it, without closing its bus name, so we are
        // not able to understand whe they're gone.
        // Thus we just kill it when an expected well-known method is failing.
        if (this.status !== SNIStatus.PASSIVE && this._checkIfReady()) {
            if (this._checkAliveTimeout) {
                this._checkAliveTimeout.cancel();
                delete this._checkAliveTimeout;
            }
            return;
        }

        if (this._checkAliveTimeout)
            return;

        try {
            const cancellable = this._cancellable;
            this._checkAliveTimeout = new PromiseUtils.TimeoutSecondsPromise(10,
                GLib.PRIORITY_DEFAULT_IDLE, cancellable);
            Util.Logger.debug(`${this.uniqueId}: may not respond, checking...`);
            await this._checkAliveTimeout;

            // We should call the Ping method instead but in some containers
            // such as snaps that's not accessible, so let's just use our own
            await this._proxy.getProperty('Status', cancellable);
        } catch (e) {
            if (e.matches(Gio.DBusError, Gio.DBusError.NAME_HAS_NO_OWNER) ||
                e.matches(Gio.DBusError, Gio.DBusError.SERVICE_UNKNOWN) ||
                e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_OBJECT) ||
                e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_INTERFACE) ||
                e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_METHOD) ||
                e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_PROPERTY)) {
                Util.Logger.warn(`${this.uniqueId}: not on bus anymore, removing it`);
                this.destroy();
                return;
            }

            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                logError(e);
        } finally {
            delete this._checkAliveTimeout;
        }
    }

    _onPropertiesChanged(_proxy, changed, _invalidated) {
        let props = Object.keys(changed.unpack());
        let signalsToEmit = new Set();
        const checkIfReadyChanged = () => {
            if (checkIfReadyChanged.value === undefined)
                checkIfReadyChanged.value = this._checkIfReady();
            return checkIfReadyChanged.value;
        };

        props.forEach(property => {
            // some property changes require updates on our part,
            // a few need to be passed down to the displaying code
            if (property === 'Id')
                checkIfReadyChanged();

            // all these can mean that the icon has to be changed
            if (property.startsWith('Icon') ||
                property.startsWith('AttentionIcon'))
                signalsToEmit.add('icon');

            // same for overlays
            if (property.startsWith('OverlayIcon'))
                signalsToEmit.add('overlay-icon');

            // this may make all of our icons invalid
            if (property === 'IconThemePath') {
                signalsToEmit.add('icon');
                signalsToEmit.add('overlay-icon');
            }

            // the label will be handled elsewhere
            if (property === 'XAyatanaLabel')
                signalsToEmit.add('label');

            if (property === 'Menu') {
                if (!checkIfReadyChanged() && this.isReady)
                    signalsToEmit.add('menu');
            }

            if (property === 'IconAccessibleDesc' ||
                property === 'AttentionAccessibleDesc' ||
                property === 'Title')
                signalsToEmit.add('accessible-name');

            // status updates may cause the indicator to be hidden
            if (property === 'Status') {
                signalsToEmit.add('icon');
                signalsToEmit.add('overlay-icon');
                signalsToEmit.add('status');
                signalsToEmit.add('accessible-name');
            }
        });

        signalsToEmit.forEach(s => this.emit(s));
    }

    reset() {
        this.emit('reset');
    }

    destroy() {
        this.emit('destroy');

        this.disconnectAll();
        this._proxy.destroy();
        this._cancellable.cancel();
        this._invalidatedPixmapsIcons.clear();

        if (this._nameWatcher)
            this._nameWatcher.destroy();
        delete this._cancellable;
        delete this._proxy;
        delete this._nameWatcher;
    }

    _getPixmapProperty(iconType) {
        const propertyName = SNIconType.toPropertyName(iconType,
            { isPixbuf: true });
        const pixmap = this._proxy.get_cached_property(propertyName);
        const wasInvalidated = this._invalidatedPixmapsIcons.delete(iconType);

        if (!pixmap && wasInvalidated) {
            this._proxy.refreshProperty(propertyName, {
                skipEqualityCheck: true,
            }).catch(e => {
                if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                    logError(e);
            });
        }

        return pixmap;
    }

    invalidatePixmapProperty(iconType) {
        this._invalidatedPixmapsIcons.add(iconType);
        this._proxy.set_cached_property(
            SNIconType.toPropertyName(iconType, { isPixbuf: true }), null);
    }

    _getActivationToken(timestamp) {
        const launchContext = global.create_app_launch_context(timestamp, -1);
        const fakeAppInfo = Gio.AppInfo.create_from_commandline(
            this._commandLine || 'true', this.id,
            Gio.AppInfoCreateFlags.SUPPORTS_STARTUP_NOTIFICATION);
        return [launchContext, launchContext.get_startup_notify_id(fakeAppInfo, [])];
    }

    async provideActivationToken(timestamp) {
        if (this._hasProvideXdgActivationToken === false)
            return;

        const [launchContext, activationToken] = this._getActivationToken(timestamp);
        try {
            await this._proxy.ProvideXdgActivationTokenAsync(activationToken,
                this._cancellable);
            this._hasProvideXdgActivationToken = true;
        } catch (e) {
            launchContext.launch_failed(activationToken);

            if (e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_METHOD))
                this._hasProvideXdgActivationToken = false;
            else
                Util.Logger.warn(`${this.id}, failed to provide activation token: ${e.message}`);
        }
    }

    async open(x, y, timestamp) {
        const cancellable = this._cancellable;
        // we can't use WindowID because we're not able to get the x11 window id from a MetaWindow
        // nor can we call any X11 functions. Luckily, the Activate method usually works fine.
        // parameters are "an hint to the item where to show eventual windows" [sic]
        // ... and don't seem to have any effect.

        try {
            await this.provideActivationToken(timestamp);
            await this._proxy.ActivateAsync(x, y, cancellable);
            this.supportsActivation = true;
        } catch (e) {
            if (e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_METHOD)) {
                this.supportsActivation = false;
                Util.Logger.warn(`${this.id}, does not support activation: ${e.message}`);
                return;
            }

            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                Util.Logger.critical(`${this.id}, failed to activate: ${e.message}`);
        }
    }

    async secondaryActivate(timestamp, x, y) {
        const cancellable = this._cancellable;

        try {
            await this.provideActivationToken(timestamp);

            if (this._hasAyatanaSecondaryActivate !== false) {
                try {
                    await this._proxy.XAyatanaSecondaryActivateAsync(timestamp, cancellable);
                    this._hasAyatanaSecondaryActivate = true;
                } catch (e) {
                    if (e.matches(Gio.DBusError, Gio.DBusError.UNKNOWN_METHOD))
                        this._hasAyatanaSecondaryActivate = false;
                    else
                        throw e;
                }
            }

            if (!this._hasAyatanaSecondaryActivate)
                await this._proxy.SecondaryActivateAsync(x, y, cancellable);
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                Util.Logger.critical(`${this.id}, failed to secondary activate: ${e.message}`);
        }
    }

    async scroll(dx, dy) {
        const cancellable = this._cancellable;

        try {
            const actions = [];

            if (dx !== 0) {
                actions.push(this._proxy.ScrollAsync(Math.floor(dx),
                    'horizontal', cancellable));
            }

            if (dy !== 0) {
                actions.push(this._proxy.ScrollAsync(Math.floor(dy),
                    'vertical', cancellable));
            }

            await Promise.all(actions);
        } catch (e) {
            Util.Logger.critical(`${this.id}, failed to scroll: ${e.message}`);
        }
    }
};
Signals.addSignalMethods(AppIndicator.prototype);

let StTextureCacheSkippingGIcon;

if (imports.system.version >= 17501) {
    try {
        StTextureCacheSkippingGIcon = GObject.registerClass({
            Implements: [Gio.Icon],
        }, class StTextureCacheSkippingGIconClass extends Gio.EmblemedIcon {
            vfunc_to_tokens() {
                // Disables the to_tokens() vfunc so that the icon to_string()
                // method won't work and thus can't be kept forever around by
                // StTextureCache, see the awesome debugging session in this thread:
                //   https://twitter.com/mild_sunrise/status/1458739604098621443
                // upstream bug is at:
                //   https://gitlab.gnome.org/GNOME/gnome-shell/-/issues/4944
                return [false, [], 0];
            }
        });
    } catch (e) {}
}

var IconActor = GObject.registerClass({
    Signals: {
        'requires-custom-image': {},
    },
},
class AppIndicatorsIconActor extends St.Icon {

    _init(indicator, iconSize) {
        super._init({
            reactive: true,
            style_class: 'system-status-icon',
            fallback_icon_name: 'image-loading-symbolic',
        });

        this.name = this.constructor.name;
        this.add_style_class_name('appindicator-icon');
        this.add_style_class_name('status-notifier-icon');
        this.set_style('padding:0');

        let themeContext = St.ThemeContext.get_for_stage(global.stage);
        this.height = iconSize * themeContext.scale_factor;

        this._indicator     = indicator;
        this._customIcons   = new Map();
        this._iconSize      = iconSize;
        this._iconCache     = new IconCache.IconCache();
        this._cancellable   = new Gio.Cancellable();
        this._loadingIcons  = Object.create(null);

        Object.values(SNIconType).forEach(t => (this._loadingIcons[t] = new Map()));

        Util.connectSmart(this._indicator, 'icon', this, () => this._updateIcon().catch(logError));
        Util.connectSmart(this._indicator, 'overlay-icon', this, this._updateOverlayIcon);
        Util.connectSmart(this._indicator, 'reset', this, () => this._invalidateIcon());

        const settings = SettingsManager.getDefaultGSettings();
        Util.connectSmart(settings, 'changed::icon-size', this, () => this._invalidateIcon());
        Util.connectSmart(settings, 'changed::custom-icons', this, () => {
            this._updateCustomIcons();
            this._invalidateIcon();
        });

        if (GObject.signal_lookup('resource-scale-changed', this))
            this.connect('resource-scale-changed', () => this._invalidateIcon());
        else
            this.connect('notify::resource-scale', () => this._invalidateIcon());

        Util.connectSmart(themeContext, 'notify::scale-factor', this, tc => {
            this.height = iconSize * tc.scale_factor;
            this._invalidateIcon();
        });

        Util.connectSmart(this._indicator, 'ready', this, () => {
            this._updateIconClass();
            this._updateCustomIcons();
            this._invalidateIcon();
        });

        Util.connectSmart(Util.getDefaultTheme(), 'changed', this, this._invalidateIcon);

        if (indicator.isReady) {
            this._updateCustomIcons();

            if (this.get_stage()) {
                this._invalidateIcon();
            } else {
                const id = this.connect('parent-set', () => {
                    if (this.get_stage()) {
                        this.disconnect(id);
                        this._invalidateIcon();
                    }
                });
            }
        }

        this.connect('destroy', () => {
            this._iconCache.destroy();
            this._cancellable.cancel();
            this._cancellable = null;
            this._indicator = null;
            this._loadingIcons = null;
        });
    }

    get debugId() {
        return this._indicator ? this._indicator.id : this.toString();
    }

    _updateIconClass() {
        if (!this._indicator)
            return;

        this.add_style_class_name(
            `appindicator-icon-${this._indicator.id.toLowerCase().replace(/_|\s/g, '-')}`);
    }

    _cancelLoadingByType(iconType) {
        this._loadingIcons[iconType].forEach(c => c.cancel());
        this._loadingIcons[iconType].clear();
    }

    _ensureNoIconIsLoading(iconType, id) {
        if (this._loadingIcons[iconType].has(id)) {
            Util.Logger.debug(`${this.debugId}, Icon ${id} Is still loading, ignoring the request`);
            throw new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING,
                'Already in progress');
        } else if (this._loadingIcons[iconType].size > 0) {
            throw new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.EXISTS,
                'Another icon is already loading');
        }
    }

    _getIconLoadingCancellable(iconType, loadingId) {
        try {
            this._ensureNoIconIsLoading(iconType, loadingId);
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.EXISTS))
                throw e;
            this._cancelLoadingByType(iconType);
        }

        const cancellable = new Util.CancellableChild(this._cancellable);
        this._loadingIcons[iconType].set(loadingId, cancellable);

        return cancellable;
    }

    _cleanupIconLoadingCancellable(iconType, loadingId) {
        if (this._loadingIcons)
            this._loadingIcons[iconType].delete(loadingId);
    }

    _getResourceScale() {
        // Remove this when we remove support for versions earlier than 3.38
        const resourceScale = this.get_resource_scale();
        if (Array.isArray(resourceScale))
            return resourceScale[0] ? resourceScale[1] : 1.0;

        return resourceScale;
    }

    // Will look the icon up in the cache, if it's found
    // it will return it. Otherwise, it will create it and cache it.
    async _cacheOrCreateIconByName(iconType, iconSize, iconScaling, iconName, themePath) {
        const id = `${iconType}:${iconName}@${iconSize * iconScaling}:${themePath || ''}`;
        let gicon = this._iconCache.get(id);

        if (gicon)
            return gicon;

        const iconInfo = this._getIconInfo(iconName, themePath, iconSize, iconScaling);
        const loadingId = iconInfo.path || id;

        const cancellable = await this._getIconLoadingCancellable(iconType, id);
        try {
            gicon = await this._createIconByIconData(iconInfo, iconSize,
                iconScaling, cancellable);
        } finally {
            this._cleanupIconLoadingCancellable(iconType, loadingId);
        }
        if (gicon)
            gicon = this._iconCache.add(id, gicon);
        return gicon;
    }

    _getIconLookupFlags(themeNode) {
        // FIXME: Use St version if available (>= 44)
        let lookupFlags = 0;

        if (!themeNode)
            return lookupFlags;

        const lookupFlagsEnum = St.IconLookupFlags || Gtk.IconLookupFlags;
        const iconStyle = themeNode.get_icon_style();
        if (iconStyle === St.IconStyle.REGULAR)
            lookupFlags |= lookupFlagsEnum.FORCE_REGULAR;
        else if (iconStyle === St.IconStyle.SYMBOLIC)
            lookupFlags |= lookupFlagsEnum.FORCE_SYMBOLIC;

        if (Clutter.get_default_text_direction() === Clutter.TextDirection.RTL)
            lookupFlags |= lookupFlagsEnum.DIR_RTL;
        else
            lookupFlags |= lookupFlagsEnum.DIR_LTR;

        return lookupFlags;
    }

    _getIconLoadingColors(themeNode) {
        if (!themeNode)
            return null;

        const iconColors = themeNode.get_icon_colors();
        if (St.IconTheme)
            return iconColors;

        if (!iconColors)
            return iconColors;

        const rgbaFromClutter = color => new Gdk.RGBA({
            red: color.red / 255.0,
            green: color.green / 255.0,
            blue: color.blue / 255.0,
            alpha: color.alpha / 255.0,
        });

        return {
            foreground: rgbaFromClutter(iconColors.foreground),
            warning: rgbaFromClutter(iconColors.warning),
            error: rgbaFromClutter(iconColors.error),
            success: rgbaFromClutter(iconColors.success),
        };
    }

    async _createIconByFile(file, iconSize, iconScaling, cancellable) {
        try {
            const inputStream = await file.read_async(GLib.PRIORITY_DEFAULT, cancellable);
            return GdkPixbuf.Pixbuf.new_from_stream_at_scale_async(inputStream,
                -1, Math.ceil(iconSize * iconScaling), true, cancellable);
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
                Util.Logger.warn(
                    `${this.debugId}, Impossible to read image from path '${file.get_path()}': ${e}`);
            }
            throw e;
        }
    }

    async _createIconByIconInfo(iconInfo, iconSize, iconScaling, cancellable) {
        const themeNode = this.get_theme_node();
        const iconColors = this._getIconLoadingColors(themeNode);

        if (iconColors) {
            const args = St.IconInfo && iconInfo instanceof St.IconInfo
                ? [iconColors] : [iconColors.foreground, iconColors.success,
                    iconColors.warning, iconColors.error];

            const [pixbuf] = await iconInfo.load_symbolic_async(...args, cancellable);
            return pixbuf;
        }

        return this._createIconByFile(Gio.File.new_for_path(iconInfo.get_filename()),
            iconSize, iconScaling, cancellable);
    }

    async _createIconByIconData({ iconInfo, path }, iconSize, iconScaling, cancellable) {
        if (!path && !iconInfo) {
            if (this._createIconIdle) {
                throw new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING,
                    'Already in progress');
            }

            try {
                this._createIconIdle = new PromiseUtils.IdlePromise(GLib.PRIORITY_DEFAULT_IDLE,
                    cancellable);
                await this._createIconIdle;
            } catch (e) {
                if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                    logError(e);
                throw e;
            } finally {
                delete this._createIconIdle;
            }
            return null;
        } else if (this._createIconIdle) {
            this._createIconIdle.cancel();
            delete this._createIconIdle;
        }

        try {
            const [format, width, height] = await GdkPixbuf.Pixbuf.get_file_info_async(
                path, cancellable);

            if (!format) {
                Util.Logger.critical(`${this.debugId}, Invalid image format: ${path}`);
                return null;
            }

            if (width >= height * 1.5) {
                /* Hello indicator-multiload! */
                await this._loadCustomImage(Gio.File.new_for_path(path),
                    width, height, cancellable);
                return null;
            } else if (StTextureCacheSkippingGIcon) {
                /* We'll wrap the icon so that it won't be cached forever by the shell */
                return new Gio.FileIcon({ file: Gio.File.new_for_path(path) });
            } else if (iconInfo) {
                return this._createIconByIconInfo(iconInfo, iconSize,
                    iconScaling, cancellable);
            } else {
                return this._createIconByFile(Gio.File.new_for_path(path),
                    iconSize, iconScaling, cancellable);
            }
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
                Util.Logger.warn(
                    `${this.debugId}, Impossible to read image info from path '${path}': ${e}`);
            }
            throw e;
        }
    }

    async _loadCustomImage(file, width, height, cancellable) {
        if (!(this instanceof CustomImageIconActor)) {
            this.emit('requires-custom-image');
            throw new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED,
                'Loading cancelled, need specific class');
        }

        const { scaleFactor } = St.ThemeContext.get_for_stage(global.stage);
        const textureCache = St.TextureCache.get_default();
        const resourceScale = this._getResourceScale();

        const customImage = textureCache.load_file_async(file, -1,
            height, scaleFactor, resourceScale);

        customImage.set({
            xAlign: imports.gi.Clutter.ActorAlign.CENTER,
            yAlign: imports.gi.Clutter.ActorAlign.CENTER,
        });

        if (customImage.content) {
            this._setCustomImage(customImage, width, height);
            return;
        }

        const imageContentPromise = new PromiseUtils.SignalConnectionPromise(
            customImage, 'notify::content', cancellable);
        const waitPromise = new PromiseUtils.TimeoutSecondsPromise(
            1, GLib.PRIORITY_DEFAULT, cancellable);

        const racingPromises = [imageContentPromise, waitPromise];

        try {
            await Promise.race(racingPromises);
            if (!waitPromise.resolved())
                this._setCustomImage(customImage, width, height);
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                throw e;
        } finally {
            racingPromises.forEach(p => p.cancel());

            if (this._customImage !== customImage)
                customImage.destroy();
        }
    }

    _setCustomImage(imageActor, width, height) {
        if (this._customImage)
            this._customImage.destroy();

        this._customImage = imageActor;
        this.add_child(this._customImage);
        this.width = width;
        this.height = height;
    }

    _getIconInfo(name, themePath, size, scale) {
        if (name && name[0] === '/') {
            // HACK: icon is a path name. This is not specified by the api but at least inidcator-sensors uses it.
            return { iconInfo: null, path: name };
        } else if (name) {
            // we manually look up the icon instead of letting st.icon do it for us
            // this allows us to sneak in an indicator provided search path and to avoid ugly upscaled icons

            // indicator-application looks up a special "panel" variant, we just replicate that here
            name += '-panel';

            // icon info as returned by the lookup
            let iconInfo = null;

            // we try to avoid messing with the default icon theme, so we'll create a new one if needed
            let iconTheme = null;
            const defaultTheme = Util.getDefaultTheme();
            if (themePath) {
                iconTheme = St.IconTheme ? new St.IconTheme() : new Gtk.IconTheme();
                defaultTheme.get_search_path().forEach(p =>
                    iconTheme.append_search_path(p));
                iconTheme.append_search_path(themePath);

                if (!Meta.is_wayland_compositor() && !St.IconTheme) {
                    const defaultScreen = imports.gi.Gdk.Screen.get_default();
                    if (defaultScreen)
                        iconTheme.set_screen(defaultScreen);
                }
            } else {
                iconTheme = defaultTheme;
            }
            if (iconTheme) {
                // try to look up the icon in the icon theme
                iconInfo = iconTheme.lookup_icon_for_scale(name, size, scale,
                    this._getIconLookupFlags(this.get_theme_node()) |
                    (St.IconLookupFlags
                        ? St.IconLookupFlags.GENERIC_FALLBACK
                        : Gtk.IconLookupFlags.GENERIC_FALLBACK));
                // no icon? that's bad!
                if (iconInfo === null) {
                    const msg = `${this.debugId}, Impossible to lookup icon for '${name}' in`;
                    Util.Logger.warn(`${msg} ${themePath ? `path ${themePath}` : 'default theme'}`);
                } else { // we have an icon
                    // get the icon path
                    return { iconInfo, path: iconInfo.get_filename() };
                }
            }
        }
        return { iconInfo: null, path: null };
    }

    async _argbToRgba(src, cancellable) {
        await new PromiseUtils.IdlePromise(GLib.PRIORITY_LOW, cancellable);

        return PixmapsUtils.argbToRgba(src);
    }

    async _createIconFromPixmap(iconType, iconSize, iconScaling, pixmapsVariant) {
        iconSize *= iconScaling;

        const { pixmapVariant, width, height, rowStride } =
            PixmapsUtils.getBestPixmap(pixmapsVariant, iconSize);

        const id = `__PIXMAP_ICON_${width}x${height}`;

        const cancellable = this._getIconLoadingCancellable(iconType, id);
        try {
            return GdkPixbuf.Pixbuf.new_from_bytes(
                await this._argbToRgba(pixmapVariant.deep_unpack(), cancellable),
                GdkPixbuf.Colorspace.RGB, true,
                8, width, height, rowStride);
        } catch (e) {
            // the image data was probably bogus. We don't really know why, but it _does_ happen.
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                Util.Logger.warn(`${this.debugId}, Impossible to create image from data: ${e}`);
            throw e;
        } finally {
            this._cleanupIconLoadingCancellable(iconType, id);
        }
    }

    // The icon cache Active flag will be set to true if the used gicon matches
    // the cached one (as in some cases it may be equal, but not the same object).
    // So when it's not need anymore we make sure to check the active state
    // and set it to false so that it can be picked up by the garbage collector.
    _setGicon(iconType, gicon, iconSize) {
        if (iconType !== SNIconType.OVERLAY) {
            if (gicon) {
                const isPixbuf = gicon instanceof GdkPixbuf.Pixbuf;
                this.gicon = StTextureCacheSkippingGIcon && !isPixbuf
                    ? new StTextureCacheSkippingGIcon({ gicon })
                    : new Gio.EmblemedIcon({ gicon });

                this._iconCache.updateActive(SNIconType.NORMAL, gicon,
                    this.gicon.get_icon() === gicon);

                this.set_icon_size(iconSize);
            } else {
                this.gicon = null;
            }
        } else if (gicon) {
            this._emblem = new Gio.Emblem({ icon: gicon });
            this._iconCache.updateActive(iconType, gicon, true);
        } else {
            this._emblem = null;
        }

        if (this.gicon) {
            if (!this.gicon.get_emblems().some(e => e.equal(this._emblem))) {
                this.gicon.clear_emblems();
                if (this._emblem)
                    this.gicon.add_emblem(this._emblem);
            }
        }
    }

    async _updateIconByType(iconType, iconSize) {
        let icon;
        switch (iconType) {
        case SNIconType.ATTENTION:
            icon = this._indicator.attentionIcon;
            break;
        case SNIconType.NORMAL:
            icon = this._indicator.icon;
            break;
        case SNIconType.OVERLAY:
            icon = this._indicator.overlayIcon;
            break;
        }

        const { theme, name, pixmap } = icon;
        const commonArgs = [theme, iconType, iconSize];

        if (this._customIcons.size) {
            let customIcon = this._customIcons.get(iconType);
            if (!await this._createAndSetIcon(customIcon, null, ...commonArgs)) {
                if (iconType !== SNIconType.OVERLAY) {
                    customIcon = this._customIcons.get(SNIconType.NORMAL);
                    await this._createAndSetIcon(customIcon, null, ...commonArgs);
                }
            }
        } else {
            await this._createAndSetIcon(name, pixmap, ...commonArgs);
        }
    }

    async _createAndSetIcon(name, pixmap, theme, iconType, iconSize) {
        let gicon = null;

        try {
            gicon = await this._createIcon(name, pixmap, theme, iconType, iconSize);
        } catch (e) {
            if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED) ||
                e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING))
                return null;


            if (iconType === SNIconType.OVERLAY)
                logError(e, `${this.debugId} unable to update icon emblem`);
            else
                logError(e, `${this.debugId} unable to update icon`);
        }

        try {
            this._setGicon(iconType, gicon, iconSize);

            if (pixmap && this.gicon) {
                // The pixmap has been saved, we can free the variants memory
                this._indicator.invalidatePixmapProperty(iconType);
            }

            return gicon;
        } catch (e) {
            logError(e, 'Setting GIcon failed');
            return null;
        }
    }

    // updates the base icon
    async _createIcon(name, pixmap, theme, iconType, iconSize) {
        const { scaleFactor } = St.ThemeContext.get_for_stage(global.stage);
        const resourceScale = this._getResourceScale();
        const iconScaling = Math.ceil(resourceScale * scaleFactor);

        // From now on we consider them the same thing, as one replaces the other
        if (iconType === SNIconType.ATTENTION)
            iconType = SNIconType.NORMAL;

        if (name) {
            const gicon = await this._cacheOrCreateIconByName(
                iconType, iconSize, iconScaling, name, theme);
            if (gicon)
                return gicon;
        }

        if (pixmap && pixmap.n_children())
            return this._createIconFromPixmap(iconType, iconSize, iconScaling, pixmap);

        return null;
    }

    // updates the base icon
    async _updateIcon() {
        if (this._indicator.status === SNIStatus.PASSIVE)
            return;

        if (this.gicon instanceof Gio.EmblemedIcon) {
            const { gicon } = this.gicon;
            this._iconCache.updateActive(SNIconType.NORMAL, gicon, false);
        }

        // we might need to use the AttentionIcon*, which have precedence over the normal icons
        let iconType = this._indicator.status === SNIStatus.NEEDS_ATTENTION
            ? SNIconType.ATTENTION : SNIconType.NORMAL;

        this._updateIconSize();

        try {
            await this._updateIconByType(iconType, this._iconSize);
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED) &&
                !e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING))
                logError(e, `${this.debugId}: Updating icon type ${iconType} failed`);
        }
    }

    async _updateOverlayIcon() {
        if (this._indicator.status === SNIStatus.PASSIVE)
            return;

        if (this._emblem) {
            const { icon } = this._emblem;
            this._iconCache.updateActive(SNIconType.OVERLAY, icon, false);
        }

        // KDE hardcodes the overlay icon size to 10px (normal icon size 16px)
        // we approximate that ratio for other sizes, too.
        // our algorithms will always pick a smaller one instead of stretching it.
        let iconSize = Math.floor(this._iconSize / 1.6);

        try {
            await this._updateIconByType(SNIconType.OVERLAY, iconSize);
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED) &&
                !e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING))
                logError(e, `${this.debugId}: Updating overlay icon failed`);
        }
    }

    // called when the icon theme changes
    _invalidateIcon() {
        this._iconCache.clear();
        this._cancellable.cancel();
        this._cancellable = new Gio.Cancellable();
        Object.values(SNIconType).forEach(iconType =>
            this._loadingIcons[iconType].clear());

        this._updateIcon().catch(e => logError(e));
        this._updateOverlayIcon().catch(e => logError(e));
    }

    _updateIconSize() {
        const settings = SettingsManager.getDefaultGSettings();
        const sizeValue = settings.get_int('icon-size');
        if (sizeValue > 0) {
            if (!this._defaultIconSize)
                this._defaultIconSize = this._iconSize;

            this._iconSize = sizeValue;
        } else if (this._defaultIconSize) {
            this._iconSize = this._defaultIconSize;
            delete this._defaultIconSize;
        }
    }

    _updateCustomIcons() {
        const settings = SettingsManager.getDefaultGSettings();
        this._customIcons.clear();

        settings.get_value('custom-icons').deep_unpack().forEach(customIcons => {
            const [indicatorId, normalIcon, attentionIcon] = customIcons;
            if (this._indicator.id === indicatorId) {
                this._customIcons.set(SNIconType.NORMAL, normalIcon);
                this._customIcons.set(SNIconType.ATTENTION, attentionIcon);
            }
        });
    }
});

var CustomImageIconActor = GObject.registerClass(
class CustomImageIconActor extends IconActor {
    vfunc_paint(paintContext) {
        if (this._customImage) {
            this.paint_background(paintContext);
            this._customImage.paint(paintContext);
            return;
        }

        super.vfunc_paint(paintContext);
    }
});