Codebase list gnome-shell-extension-appindicator / 66871f7b-41e9-439a-a449-7c24d336c105/main appIndicator.js
66871f7b-41e9-439a-a449-7c24d336c105/main

Tree @66871f7b-41e9-439a-a449-7c24d336c105/main (Download .tar.gz)

appIndicator.js @66871f7b-41e9-439a-a449-7c24d336c105/main

e2de1b7
2d2d1f7
 
 
 
 
cdaad01
2d2d1f7
 
 
 
 
 
 
 
 
f5fe477
 
5248b0b
 
 
 
 
d40f06f
5248b0b
2d2d1f7
 
5248b0b
90c376a
ceaa709
2fbfdcc
83fce78
45c6f04
dc436b2
45c6f04
0462445
 
 
 
 
2d2d1f7
89368f3
 
f5fe477
2d2d1f7
 
 
 
5248b0b
2d2d1f7
 
1dc5e56
2d2d1f7
 
5248b0b
2d2d1f7
 
8b84559
 
 
 
 
 
2fb515a
 
 
 
f5fe477
cdaad01
f5fe477
 
 
ea45060
4a869e4
f5fe477
83fce78
5248b0b
83fce78
3852a46
83fce78
f5fe477
 
 
5248b0b
 
83fce78
c447392
7b926ae
5248b0b
7b926ae
426880e
f5fe477
6adc5be
96e5e32
7b926ae
426880e
0eec646
 
c447392
 
 
 
 
 
 
f5fe477
c447392
 
 
0eec646
 
 
 
426880e
0eec646
 
 
76569a0
0eec646
 
758c94b
3b02297
758c94b
 
 
0eec646
 
 
 
 
 
 
3b02297
 
 
 
 
 
 
 
f5fe477
3b02297
 
 
 
 
 
 
0eec646
426880e
0eec646
3b02297
 
426880e
 
f7d9118
cdaad01
f7d9118
76569a0
 
 
 
 
 
 
 
 
 
5248b0b
76569a0
 
e32877a
 
f7d9118
e32877a
76569a0
 
 
 
f5fe477
76569a0
 
 
 
 
ed44631
 
76569a0
 
 
4a869e4
89368f3
e32877a
 
8b18dee
5248b0b
8b18dee
5248b0b
cdaad01
8d53529
 
4a869e4
ed44631
8d53529
5248b0b
 
 
 
f7d9118
cdaad01
3b02297
ea45060
89368f3
3b02297
89368f3
 
3b02297
 
 
 
5248b0b
ea45060
3b02297
 
 
89368f3
 
5248b0b
280af56
83fce78
f7d9118
5248b0b
280af56
83fce78
f7d9118
5248b0b
95ce63a
 
f7d9118
5248b0b
280af56
83fce78
f7d9118
5248b0b
280af56
e32877a
f7d9118
5248b0b
ed44631
 
 
 
 
 
 
5289ceb
f5fe477
0eec646
 
 
f7d9118
cdaad01
5ed40db
 
83fce78
 
5248b0b
 
f7d9118
5ed40db
 
 
83fce78
 
5248b0b
 
f7d9118
5ed40db
 
 
83fce78
 
5248b0b
 
f7d9118
5ed40db
426880e
96e5e32
 
426880e
 
46b757d
 
 
 
f5fe477
64c6ba7
3510c9a
4a869e4
5248b0b
83fce78
 
4a869e4
83fce78
c5314ca
5248b0b
 
 
7e7a328
83fce78
8b18dee
5248b0b
83fce78
 
f5fe477
5248b0b
 
83fce78
7e7a328
83fce78
f5fe477
5248b0b
4a869e4
f5fe477
0eec646
5248b0b
0eec646
 
ed44631
 
 
 
 
83fce78
c5314ca
 
5248b0b
ed44631
c5314ca
3510c9a
 
 
f7d9118
cdaad01
f7d9118
5c11c84
f7d9118
2d2d1f7
f7d9118
5248b0b
4a869e4
5248b0b
3852a46
faa9fcd
f5fe477
 
3852a46
3b02297
f5fe477
f7d9118
2d2d1f7
f7d9118
5ed40db
 
 
 
5248b0b
f7d9118
9dcf3fc
f7d9118
5248b0b
f7d9118
6fbe4d3
f7d9118
f5fe477
5248b0b
9dcf3fc
f5fe477
5248b0b
5ed40db
f7d9118
5ed40db
 
f7d9118
f5fe477
f7d9118
f5fe477
8b84559
 
32f2f34
8b84559
 
 
f7d9118
8b84559
b46eba9
32f2f34
5ed40db
f5fe477
988bb05
f5fe477
5ed40db
5248b0b
f5fe477
5248b0b
8b84559
d08bb6f
5ed40db
7b926ae
 
 
1969d16
dc436b2
 
2224b3f
5248b0b
f5fe477
8b84559
988bb05
1969d16
8b84559
 
 
5248b0b
8b84559
d40f06f
5ed40db
 
5248b0b
f7d9118
 
 
8b84559
f7d9118
 
5ed40db
8b84559
 
 
 
 
a6a8a81
 
 
 
 
 
 
 
5ed40db
 
45c6f04
f5fe477
 
 
8b84559
6c347e2
45c6f04
 
6c347e2
d08bb6f
 
45c6f04
 
a6a8a81
 
d08bb6f
6c347e2
d08bb6f
f5fe477
45c6f04
 
 
 
 
f7d9118
5ed40db
45c6f04
8b84559
45c6f04
 
 
 
 
 
 
 
 
 
 
8b84559
 
45c6f04
745c66a
45c6f04
 
 
 
42e8dce
45c6f04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745c66a
42e8dce
45c6f04
 
 
8b84559
45c6f04
 
 
 
8b84559
45c6f04
 
 
 
 
 
5248b0b
45c6f04
8b84559
45c6f04
 
 
 
 
bac3f1c
cdaad01
305007c
bac3f1c
f5fe477
5248b0b
8b84559
bac3f1c
b289f60
 
cdaad01
bac3f1c
5248b0b
bac3f1c
b289f60
bac3f1c
fff5521
ee77b86
f5fe477
d40f06f
5ed40db
f5fe477
d40f06f
f5fe477
 
d40f06f
 
 
 
 
 
ee77b86
d40f06f
7755d51
f5fe477
bac3f1c
f5fe477
305007c
bac3f1c
 
8b61cee
 
bac3f1c
 
 
94efd82
2d2d1f7
280af56
8b84559
f7d9118
7e7a328
8f05f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
5248b0b
8f05f7c
 
 
 
 
 
 
 
005fe8b
8f05f7c
8b84559
 
8f05f7c
8b84559
 
 
45c6f04
f5fe477
 
 
7e7a328
 
 
 
 
45c6f04
7e7a328
24cd905
 
5248b0b
 
7e7a328
5248b0b
 
7e7a328
24cd905
 
5248b0b
5ed40db
5248b0b
 
5ed40db
5248b0b
 
5ed40db
8f05f7c
 
 
 
 
 
 
 
 
 
 
 
24cd905
 
8f05f7c
24cd905
 
 
 
8f05f7c
 
24cd905
8f05f7c
 
24cd905
f7d9118
cdaad01
930a8c8
 
 
 
cb3ddf6
f5fe477
8b84559
 
930a8c8
 
f5fe477
cb3ddf6
 
8b84559
 
 
 
5248b0b
 
930a8c8
5248b0b
 
 
 
 
5ed40db
7e7a328
8b84559
6ebe41b
8b84559
 
 
 
 
 
5ed40db
45c6f04
8b84559
 
5248b0b
 
 
 
 
 
 
 
 
0383431
cdaad01
45c6f04
 
 
 
 
 
 
 
 
 
 
cb3ddf6
45c6f04
 
 
 
 
8b84559
 
7e7a328
8b84559
 
930a8c8
 
7e7a328
8b84559
5248b0b
5ed40db
 
8b84559
f5fe477
5248b0b
530f527
309d0ce
8b84559
f7d9118
7e7a328
f7d9118
930a8c8
 
7e7a328
930a8c8
 
4a869e4
cdaad01
7e7a328
 
 
5248b0b
7e7a328
8b84559
f7d9118
2d2d1f7
4a869e4
f7d9118
5248b0b
a6a8a81
7e7a328
5248b0b
 
7e7a328
2224b3f
309d0ce
dc436b2
 
2224b3f
 
 
 
 
 
 
 
 
 
f7d9118
  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
// 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 AppIndicator, IconActor */

const GdkPixbuf = imports.gi.GdkPixbuf;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
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 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');

const MAX_UPDATE_FREQUENCY = 100; // In ms

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

var SNIStatus = {
    PASSIVE: 'Passive',
    ACTIVE: 'Active',
    NEEDS_ATTENTION: 'NeedsAttention',
};

const SNIconType = {
    NORMAL: 0,
    ATTENTION: 1,
    OVERLAY: 2,
};

/**
 * 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 {

    constructor(service, busName, object) {
        this.busName = busName;
        this._uniqueId = busName + object;
        this._accumulatedSignals = new Set();

        const interfaceInfo = Gio.DBusInterfaceInfo.new_for_xml(Interfaces.StatusNotifierItem);

        // HACK: we cannot use Gio.DBusProxy.makeProxyWrapper because we need
        //      to specify G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES
        this._cancellable = new Gio.Cancellable();
        this._proxy = new Gio.DBusProxy({ g_connection: Gio.DBus.session,
            g_interface_name: interfaceInfo.name,
            g_interface_info: interfaceInfo,
            g_name: busName,
            g_object_path: object,
            g_flags: Gio.DBusProxyFlags.GET_INVALIDATED_PROPERTIES });

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

        if (service !== busName && service.match(Util.BUS_ADDRESS_REGEX)) {
            this._uniqueId = service;
            this._nameWatcher = new Util.NameWatcher(service);
            Util.connectSmart(this._nameWatcher, 'changed', this, this._nameOwnerChanged);
        }
    }

    async _setupProxy() {
        try {
            await this._proxy.init_async(GLib.PRIORITY_DEFAULT, this._cancellable);
            this._checkIfReady();
            this._checkMenuReady();
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                Util.Logger.warn(`While initalizing proxy for ${this._uniqueId}: ${e}`);
        }
    }

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

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

        this.isReady = isReady;
        this._setupProxyPropertyList();

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

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

        return false;
    }

    async _checkMenuReady() {
        if (this.menuPath)
            return true;

        const cancellable = this._cancellable;
        for (let checks = 0; checks < 3 && !this.isReady; ++checks) {
            this._delayCheck = new PromiseUtils.TimeoutSecondsPromise(1,
                GLib.PRIORITY_DEFAULT_IDLE, cancellable);
            // eslint-disable-next-line no-await-in-loop
            await this._delayCheck;
            Util.refreshPropertyOnProxy(this._proxy, 'Menu');
        }

        return !!this.menuPath;
    }

    _nameOwnerChanged() {
        if (!this.hasNameOwner)
            this._checkIfReady();
        else
            this._checkMenuReady();

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

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

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

        this._proxyPropertyList.push(name);
    }

    _setupProxyPropertyList() {
        let interfaceProps = this._proxy.g_interface_info.properties;
        this._proxyPropertyList =
            (this._proxy.get_cached_property_names() || []).filter(p =>
                interfaceProps.some(propinfo => propinfo.name === p));

        if (this._proxyPropertyList.length) {
            this._addExtraProperty('XAyatanaLabel');
            this._addExtraProperty('XAyatanaLabelGuide');
            this._addExtraProperty('XAyatanaOrderingIndex');
            this._addExtraProperty('IconAccessibleDesc');
            this._addExtraProperty('AttentionAccessibleDesc');
        }
    }

    // The Author of the spec didn't like the PropertiesChanged signal, so he invented his own
    _translateNewSignals(signal) {
        let prop = null;

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

        if (!prop)
            return;

        [prop, `${prop}Name`, `${prop}Pixmap`, `${prop}AccessibleDesc`].filter(p =>
            this._proxyPropertyList.includes(p)).forEach(p =>
            Util.refreshPropertyOnProxy(this._proxy, p, {
                skipEqualityCheck: p.endsWith('Pixmap'),
            }),
        );
    }

    async _onProxySignal(_proxy, _sender, signal, _params) {
        this._accumulatedSignals.add(signal);

        if (this._signalsAccumulator)
            return;

        this._signalsAccumulator = new PromiseUtils.TimeoutPromise(
            GLib.PRIORITY_DEFAULT_IDLE, MAX_UPDATE_FREQUENCY, this._cancellable);
        try {
            await this._signalsAccumulator;
            this._accumulatedSignals.forEach(s => this._translateNewSignals(s));
            this._accumulatedSignals.clear();
        } finally {
            delete this._signalsAccumulator;
        }
    }

    // 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;
    }

    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 || '/MenuBar';
    }

    get attentionIcon() {
        return [
            this._proxy.AttentionIconName,
            this._proxy.AttentionIconPixmap,
            this._proxy.IconThemePath,
        ];
    }

    get icon() {
        return [
            this._proxy.IconName,
            this._proxy.IconPixmap,
            this._proxy.IconThemePath,
        ];
    }

    get overlayIcon() {
        return [
            this._proxy.OverlayIconName,
            this._proxy.OverlayIconPixmap,
            this._proxy.IconThemePath,
        ];
    }

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

    get cancellable() {
        return this._cancellable;
    }

    _onPropertiesChanged(_proxy, changed, _invalidated) {
        let props = Object.keys(changed.unpack());
        let signalsToEmit = new Set();

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

            // 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 (!this._checkIfReady() && 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('status');
                signalsToEmit.add('accessible-name');
            }
        });

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

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

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

        this.disconnectAll();
        this._cancellable.cancel();
        Util.cancelRefreshPropertyOnProxy(this._proxy);
        if (this._nameWatcher)
            this._nameWatcher.destroy();
        delete this._cancellable;
        delete this._proxy;
        delete this._nameWatcher;
    }

    open() {
        // 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.
        this._proxy.ActivateRemote(0, 0);
    }

    secondaryActivate() {
        this._proxy.SecondaryActivateRemote(0, 0);
    }

    scroll(dx, dy) {
        if (dx !== 0)
            this._proxy.ScrollRemote(Math.floor(dx), 'horizontal');

        if (dy !== 0)
            this._proxy.ScrollRemote(Math.floor(dy), 'vertical');
    }
};
Signals.addSignalMethods(AppIndicator.prototype);

var IconActor = GObject.registerClass(
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');

        // eslint-disable-next-line no-undef
        let themeContext = St.ThemeContext.get_for_stage(global.stage);
        this.height = iconSize * themeContext.scale_factor;

        this._indicator     = indicator;
        this._iconSize      = iconSize;
        this._iconCache     = new IconCache.IconCache();
        this._cancellable   = new Gio.Cancellable();
        this._loadingIcons  = new Set();

        Util.connectSmart(this._indicator, 'icon', this, this._updateIcon);
        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(themeContext, 'notify::scale-factor', this, tc => {
            this.height = iconSize * tc.scale_factor;
            this._invalidateIcon();
        });

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

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

        if (indicator.isReady)
            this._invalidateIcon();

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

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

    _cancelLoading() {
        if (this._loadingIcons.size > 0) {
            this._cancellable.cancel();
            this._cancellable = new Gio.Cancellable();
            this._loadingIcons.clear();
        }
    }

    // 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(iconSize, iconName, themePath) {
        // eslint-disable-next-line no-undef
        let { scale_factor: scaleFactor } = St.ThemeContext.get_for_stage(global.stage);
        let id = `${iconName}@${iconSize * scaleFactor}${themePath || ''}`;
        let gicon = this._iconCache.get(id);

        if (gicon)
            return gicon;

        if (this._loadingIcons.has(id)) {
            Util.Logger.debug(`${this._indicator.id}, Icon ${id} Is still loading, ignoring the request`);
            throw new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING,
                'Already in progress');
        } else {
            this._cancelLoading();
        }

        this._loadingIcons.add(id);
        let path = this._getIconInfo(iconName, themePath, iconSize, scaleFactor);
        gicon = await this._createIconByName(path);
        this._loadingIcons.delete(id);
        if (gicon)
            gicon = this._iconCache.add(id, gicon);
        return gicon;
    }

    async _createIconByPath(path, width, height) {
        let file = Gio.File.new_for_path(path);
        try {
            const inputStream = await file.read_async(GLib.PRIORITY_DEFAULT, this._cancellable);
            const pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale_async(inputStream,
                height, width, true, this._cancellable);
            this.icon_size = width > 0 ? width : this._iconSize;
            return pixbuf;
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                Util.Logger.warn(`${this._indicator.id}, Impossible to read image from path '${path}': ${e}`);
            throw e;
        }
    }

    async _createIconByName(path) {
        if (!path) {
            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,
                    this._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, this._cancellable);

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

            if (width >= height * 1.5) {
                /* Hello indicator-multiload! */
                return this._createIconByPath(path, width, -1);
            } else {
                this.icon_size = this._iconSize;
                return new Gio.FileIcon({
                    file: Gio.File.new_for_path(path),
                });
            }
        } catch (e) {
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
                Util.Logger.warn(`${this._indicator.id}, Impossible to read image info from path '${path}': ${e}`);
            throw e;
        }
    }

    _getIconInfo(name, themePath, size, scale) {
        let path = null;
        if (name && name[0] === '/') {
            // HACK: icon is a path name. This is not specified by the api but at least inidcator-sensors uses it.
            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 = new Gtk.IconTheme();
                defaultTheme.get_search_path().forEach(p =>
                    iconTheme.append_search_path(p));
                iconTheme.append_search_path(themePath);

                if (!Meta.is_wayland_compositor()) {
                    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,
                    Gtk.IconLookupFlags.GENERIC_FALLBACK);
                // no icon? that's bad!
                if (iconInfo === null) {
                    let msg = `${this._indicator.id}, 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
                    path = iconInfo.get_filename();
                }
            }
        }
        return path;
    }

    async argbToRgba(src, cancellable) {
        const CHUNK_SIZE = 1024;
        const ops = [];
        const dest = new Uint8Array(src.length);

        for (let i = 0; i < src.length;) {
            const chunkSize = Math.min(CHUNK_SIZE, src.length - i);

            ops.push(new PromiseUtils.CancellablePromise(async resolve => {
                const start = i;
                const end = i + chunkSize;
                await new PromiseUtils.IdlePromise(GLib.PRIORITY_LOW, cancellable);

                for (let j = start; j < end; j += 4) {
                    let srcAlpha = src[j];

                    dest[j] = src[j + 1]; /* red */
                    dest[j + 1] = src[j + 2]; /* green */
                    dest[j + 2] = src[j + 3]; /* blue */
                    dest[j + 3] = srcAlpha; /* alpha */
                }
                resolve();
            }, cancellable));

            i += chunkSize;
        }

        await Promise.all(ops);
        return dest;
    }

    async _createIconFromPixmap(iconSize, iconPixmapArray) {
        // eslint-disable-next-line no-undef
        const { scale_factor: scaleFactor } = St.ThemeContext.get_for_stage(global.stage);
        iconSize *= scaleFactor;
        // the pixmap actually is an array of pixmaps with different sizes
        // we use the one that is smaller or equal the iconSize

        // maybe it's empty? that's bad.
        if (!iconPixmapArray || iconPixmapArray.length < 1)
            throw TypeError('Empty Icon found');

        const sortedIconPixmapArray = iconPixmapArray.sort((pixmapA, pixmapB) => {
            // we sort smallest to biggest
            const areaA = pixmapA[0] * pixmapA[1];
            const areaB = pixmapB[0] * pixmapB[1];

            return areaA - areaB;
        });

        const qualifiedIconPixmapArray = sortedIconPixmapArray.filter(pixmap =>
            // we prefer any pixmap that is equal or bigger than our requested size
            pixmap[0] >= iconSize && pixmap[1] >= iconSize);

        const iconPixmap = qualifiedIconPixmapArray.length > 0
            ? qualifiedIconPixmapArray[0] : sortedIconPixmapArray.pop();

        const [width, height, bytes] = iconPixmap;
        const rowStride = width * 4; // hopefully this is correct

        const id = `__PIXMAP_ICON_${width}x${height}`;
        if (this._loadingIcons.has(id)) {
            Util.Logger.debug(`${this._indicator.id}, Pixmap ${width}x${height} ` +
                'Is still loading, ignoring the request');
            throw new GLib.Error(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING,
                'Already in progress');
        } else {
            this._cancelLoading();
        }

        this._loadingIcons.add(id);

        try {
            return GdkPixbuf.Pixbuf.new_from_bytes(
                await this.argbToRgba(bytes, this._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._indicator.id}, Impossible to create image from data: ${e}`);
            throw e;
        } finally {
            this._loadingIcons.delete(id);
        }
    }

    // The .inUse 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 .inUse property
    // 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) {
                this.gicon = new Gio.EmblemedIcon({ gicon });

                if (!(gicon instanceof GdkPixbuf.Pixbuf))
                    gicon.inUse = this.gicon.get_icon() === gicon;

                this.set_icon_size(iconSize);
            } else {
                this.gicon = null;
                Util.Logger.critical(`unable to update icon for ${this._indicator.id}`);
            }
        } else if (gicon) {
            this._emblem = new Gio.Emblem({ icon: gicon });

            if (!(gicon instanceof GdkPixbuf.Pixbuf))
                gicon.inUse = true;
        } else {
            this._emblem = null;
            Util.Logger.debug(`unable to update icon emblem for ${this._indicator.id}`);
        }

        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 [name, pixmap, theme] = icon;
        let gicon = null;
        try {
            if (name && name.length) {
                gicon = await this._cacheOrCreateIconByName(iconSize, name, theme);
                if (!gicon && pixmap)
                    gicon = await this._createIconFromPixmap(iconSize, pixmap, iconType);
            } else if (pixmap) {
                gicon = await this._createIconFromPixmap(iconSize, pixmap, iconType);
            }

            this._setGicon(iconType, gicon, iconSize);
        } catch (e) {
            /* We handle the error messages already */
            if (!e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED) &&
                !e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.PENDING))
                Util.Logger.debug(`${this._indicator.id}, Impossible to load icon: ${e}`);
        }
    }

    // updates the base icon
    _updateIcon() {
        if (this.gicon instanceof Gio.EmblemedIcon) {
            let { gicon } = this.gicon;

            if (gicon.inUse)
                gicon.inUse = 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();
        this._updateIconByType(iconType, this._iconSize);
    }

    _updateOverlayIcon() {
        if (this._emblem) {
            let { icon } = this._emblem;

            if (icon.inUse)
                icon.inUse = 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);

        this._updateIconByType(SNIconType.OVERLAY, iconSize);
    }

    // called when the icon theme changes
    _invalidateIcon() {
        this._iconCache.clear();
        this._cancelLoading();

        this._updateIcon();
        this._updateOverlayIcon();
    }

    _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;
        }
    }
});